file_name
stringlengths
4
45
method_name
stringlengths
3
58
code_before
stringlengths
980
1.05M
code_after
stringlengths
1.13k
1.05M
func_before
stringlengths
55
114k
func_after
stringlengths
71
114k
diff
stringlengths
75
133k
num_lines_added
float64
1
1.49k
num_lines_deleted
float64
1
1.13k
num_lines_in_file
float64
27
23.2k
num_tokens_in_file
float64
143
192k
repo
stringclasses
259 values
cve_id
stringlengths
13
16
cwe_id
stringclasses
73 values
print-isakmp.c
ikev1_attr_print
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; }
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; }
{'added': [(915, '\t\t const u_char *p, const u_char *ep2,'), (921, '\tND_TCHECK(p[0]);'), (924, '\telse {'), (925, '\t\tND_TCHECK_16BITS(&p[2]);'), (927, '\t}'), (928, '\tif (ep2 < p + totlen) {'), (930, '\t\treturn ep2 + 1;'), (933, '\tND_TCHECK_16BITS(&p[0]);'), (942, '\t\tND_TCHECK_16BITS(&p[2]);'), (946, '\t\telse {'), (947, '\t\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (948, '\t\t\t\tND_PRINT((ndo,")"));'), (949, '\t\t\t\tgoto trunc;'), (950, '\t\t\t}'), (951, '\t\t}'), (953, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (954, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (955, '\t\t\tND_PRINT((ndo,")"));'), (956, '\t\t\tgoto trunc;'), (957, '\t\t}'), (961, ''), (962, 'trunc:'), (963, '\treturn NULL;'), (967, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)'), (972, '\tND_TCHECK(p[0]);'), (975, '\telse {'), (976, '\t\tND_TCHECK_16BITS(&p[2]);'), (978, '\t}'), (979, '\tif (ep2 < p + totlen) {'), (981, '\t\treturn ep2 + 1;'), (984, '\tND_TCHECK_16BITS(&p[0]);'), (991, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (992, '\t\t\tND_PRINT((ndo,")"));'), (993, '\t\t\tgoto trunc;'), (994, '\t\t}'), (996, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (997, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (998, '\t\t\tND_PRINT((ndo,")"));'), (999, '\t\t\tgoto trunc;'), (1000, '\t\t}'), (1004, ''), (1005, 'trunc:'), (1006, '\treturn NULL;'), (1287, '\t\tif (map && nmap)'), (1288, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1289, '\t\telse'), (1290, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1291, '\t\tif (cp == NULL)'), (1292, '\t\t\tgoto trunc;'), (1756, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1757, '\t\t\t\tif (cp == NULL) {'), (1758, '\t\t\t\t\tND_PRINT((ndo,")"));'), (1759, '\t\t\t\t\tgoto trunc;'), (1760, '\t\t\t\t}'), (1961, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1963, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1964, '\t\tif (cp == NULL)'), (1965, '\t\t\tgoto trunc;')], 'deleted': [(915, '\t\t const u_char *p, const u_char *ep,'), (923, '\telse'), (925, '\tif (ep < p + totlen) {'), (927, '\t\treturn ep + 1;'), (941, '\t\telse'), (942, '\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (944, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (945, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (952, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)'), (959, '\telse'), (961, '\tif (ep < p + totlen) {'), (963, '\t\treturn ep + 1;'), (972, '\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (974, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (975, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (1259, '\t\tif (map && nmap) {'), (1260, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1261, '\t\t\t\tmap, nmap);'), (1262, '\t\t} else'), (1263, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);'), (1727, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,'), (1728, '\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);'), (1929, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1930, '\t\t\t\tmap, nmap);'), (1932, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);')]}
58
25
2,305
15,204
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13039
['CWE-125']
print-isakmp.c
ikev1_attrmap_print
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; }
ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; }
{'added': [(915, '\t\t const u_char *p, const u_char *ep2,'), (921, '\tND_TCHECK(p[0]);'), (924, '\telse {'), (925, '\t\tND_TCHECK_16BITS(&p[2]);'), (927, '\t}'), (928, '\tif (ep2 < p + totlen) {'), (930, '\t\treturn ep2 + 1;'), (933, '\tND_TCHECK_16BITS(&p[0]);'), (942, '\t\tND_TCHECK_16BITS(&p[2]);'), (946, '\t\telse {'), (947, '\t\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (948, '\t\t\t\tND_PRINT((ndo,")"));'), (949, '\t\t\t\tgoto trunc;'), (950, '\t\t\t}'), (951, '\t\t}'), (953, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (954, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (955, '\t\t\tND_PRINT((ndo,")"));'), (956, '\t\t\tgoto trunc;'), (957, '\t\t}'), (961, ''), (962, 'trunc:'), (963, '\treturn NULL;'), (967, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)'), (972, '\tND_TCHECK(p[0]);'), (975, '\telse {'), (976, '\t\tND_TCHECK_16BITS(&p[2]);'), (978, '\t}'), (979, '\tif (ep2 < p + totlen) {'), (981, '\t\treturn ep2 + 1;'), (984, '\tND_TCHECK_16BITS(&p[0]);'), (991, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (992, '\t\t\tND_PRINT((ndo,")"));'), (993, '\t\t\tgoto trunc;'), (994, '\t\t}'), (996, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (997, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (998, '\t\t\tND_PRINT((ndo,")"));'), (999, '\t\t\tgoto trunc;'), (1000, '\t\t}'), (1004, ''), (1005, 'trunc:'), (1006, '\treturn NULL;'), (1287, '\t\tif (map && nmap)'), (1288, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1289, '\t\telse'), (1290, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1291, '\t\tif (cp == NULL)'), (1292, '\t\t\tgoto trunc;'), (1756, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1757, '\t\t\t\tif (cp == NULL) {'), (1758, '\t\t\t\t\tND_PRINT((ndo,")"));'), (1759, '\t\t\t\t\tgoto trunc;'), (1760, '\t\t\t\t}'), (1961, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1963, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1964, '\t\tif (cp == NULL)'), (1965, '\t\t\tgoto trunc;')], 'deleted': [(915, '\t\t const u_char *p, const u_char *ep,'), (923, '\telse'), (925, '\tif (ep < p + totlen) {'), (927, '\t\treturn ep + 1;'), (941, '\t\telse'), (942, '\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (944, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (945, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (952, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)'), (959, '\telse'), (961, '\tif (ep < p + totlen) {'), (963, '\t\treturn ep + 1;'), (972, '\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (974, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (975, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (1259, '\t\tif (map && nmap) {'), (1260, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1261, '\t\t\t\tmap, nmap);'), (1262, '\t\t} else'), (1263, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);'), (1727, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,'), (1728, '\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);'), (1929, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1930, '\t\t\t\tmap, nmap);'), (1932, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);')]}
58
25
2,305
15,204
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13039
['CWE-125']
print-isakmp.c
ikev1_n_print
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; }
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; }
{'added': [(915, '\t\t const u_char *p, const u_char *ep2,'), (921, '\tND_TCHECK(p[0]);'), (924, '\telse {'), (925, '\t\tND_TCHECK_16BITS(&p[2]);'), (927, '\t}'), (928, '\tif (ep2 < p + totlen) {'), (930, '\t\treturn ep2 + 1;'), (933, '\tND_TCHECK_16BITS(&p[0]);'), (942, '\t\tND_TCHECK_16BITS(&p[2]);'), (946, '\t\telse {'), (947, '\t\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (948, '\t\t\t\tND_PRINT((ndo,")"));'), (949, '\t\t\t\tgoto trunc;'), (950, '\t\t\t}'), (951, '\t\t}'), (953, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (954, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (955, '\t\t\tND_PRINT((ndo,")"));'), (956, '\t\t\tgoto trunc;'), (957, '\t\t}'), (961, ''), (962, 'trunc:'), (963, '\treturn NULL;'), (967, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)'), (972, '\tND_TCHECK(p[0]);'), (975, '\telse {'), (976, '\t\tND_TCHECK_16BITS(&p[2]);'), (978, '\t}'), (979, '\tif (ep2 < p + totlen) {'), (981, '\t\treturn ep2 + 1;'), (984, '\tND_TCHECK_16BITS(&p[0]);'), (991, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (992, '\t\t\tND_PRINT((ndo,")"));'), (993, '\t\t\tgoto trunc;'), (994, '\t\t}'), (996, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (997, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (998, '\t\t\tND_PRINT((ndo,")"));'), (999, '\t\t\tgoto trunc;'), (1000, '\t\t}'), (1004, ''), (1005, 'trunc:'), (1006, '\treturn NULL;'), (1287, '\t\tif (map && nmap)'), (1288, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1289, '\t\telse'), (1290, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1291, '\t\tif (cp == NULL)'), (1292, '\t\t\tgoto trunc;'), (1756, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1757, '\t\t\t\tif (cp == NULL) {'), (1758, '\t\t\t\t\tND_PRINT((ndo,")"));'), (1759, '\t\t\t\t\tgoto trunc;'), (1760, '\t\t\t\t}'), (1961, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1963, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1964, '\t\tif (cp == NULL)'), (1965, '\t\t\tgoto trunc;')], 'deleted': [(915, '\t\t const u_char *p, const u_char *ep,'), (923, '\telse'), (925, '\tif (ep < p + totlen) {'), (927, '\t\treturn ep + 1;'), (941, '\t\telse'), (942, '\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (944, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (945, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (952, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)'), (959, '\telse'), (961, '\tif (ep < p + totlen) {'), (963, '\t\treturn ep + 1;'), (972, '\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (974, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (975, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (1259, '\t\tif (map && nmap) {'), (1260, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1261, '\t\t\t\tmap, nmap);'), (1262, '\t\t} else'), (1263, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);'), (1727, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,'), (1728, '\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);'), (1929, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1930, '\t\t\t\tmap, nmap);'), (1932, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);')]}
58
25
2,305
15,204
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13039
['CWE-125']
print-isakmp.c
ikev1_t_print
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; }
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; }
{'added': [(915, '\t\t const u_char *p, const u_char *ep2,'), (921, '\tND_TCHECK(p[0]);'), (924, '\telse {'), (925, '\t\tND_TCHECK_16BITS(&p[2]);'), (927, '\t}'), (928, '\tif (ep2 < p + totlen) {'), (930, '\t\treturn ep2 + 1;'), (933, '\tND_TCHECK_16BITS(&p[0]);'), (942, '\t\tND_TCHECK_16BITS(&p[2]);'), (946, '\t\telse {'), (947, '\t\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (948, '\t\t\t\tND_PRINT((ndo,")"));'), (949, '\t\t\t\tgoto trunc;'), (950, '\t\t\t}'), (951, '\t\t}'), (953, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (954, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (955, '\t\t\tND_PRINT((ndo,")"));'), (956, '\t\t\tgoto trunc;'), (957, '\t\t}'), (961, ''), (962, 'trunc:'), (963, '\treturn NULL;'), (967, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)'), (972, '\tND_TCHECK(p[0]);'), (975, '\telse {'), (976, '\t\tND_TCHECK_16BITS(&p[2]);'), (978, '\t}'), (979, '\tif (ep2 < p + totlen) {'), (981, '\t\treturn ep2 + 1;'), (984, '\tND_TCHECK_16BITS(&p[0]);'), (991, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (992, '\t\t\tND_PRINT((ndo,")"));'), (993, '\t\t\tgoto trunc;'), (994, '\t\t}'), (996, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (997, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (998, '\t\t\tND_PRINT((ndo,")"));'), (999, '\t\t\tgoto trunc;'), (1000, '\t\t}'), (1004, ''), (1005, 'trunc:'), (1006, '\treturn NULL;'), (1287, '\t\tif (map && nmap)'), (1288, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1289, '\t\telse'), (1290, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1291, '\t\tif (cp == NULL)'), (1292, '\t\t\tgoto trunc;'), (1756, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1757, '\t\t\t\tif (cp == NULL) {'), (1758, '\t\t\t\t\tND_PRINT((ndo,")"));'), (1759, '\t\t\t\t\tgoto trunc;'), (1760, '\t\t\t\t}'), (1961, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1963, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1964, '\t\tif (cp == NULL)'), (1965, '\t\t\tgoto trunc;')], 'deleted': [(915, '\t\t const u_char *p, const u_char *ep,'), (923, '\telse'), (925, '\tif (ep < p + totlen) {'), (927, '\t\treturn ep + 1;'), (941, '\t\telse'), (942, '\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (944, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (945, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (952, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)'), (959, '\telse'), (961, '\tif (ep < p + totlen) {'), (963, '\t\treturn ep + 1;'), (972, '\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (974, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (975, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (1259, '\t\tif (map && nmap) {'), (1260, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1261, '\t\t\t\tmap, nmap);'), (1262, '\t\t} else'), (1263, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);'), (1727, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,'), (1728, '\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);'), (1929, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1930, '\t\t\t\tmap, nmap);'), (1932, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);')]}
58
25
2,305
15,204
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13039
['CWE-125']
print-isakmp.c
ikev2_t_print
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; }
ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; }
{'added': [(915, '\t\t const u_char *p, const u_char *ep2,'), (921, '\tND_TCHECK(p[0]);'), (924, '\telse {'), (925, '\t\tND_TCHECK_16BITS(&p[2]);'), (927, '\t}'), (928, '\tif (ep2 < p + totlen) {'), (930, '\t\treturn ep2 + 1;'), (933, '\tND_TCHECK_16BITS(&p[0]);'), (942, '\t\tND_TCHECK_16BITS(&p[2]);'), (946, '\t\telse {'), (947, '\t\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (948, '\t\t\t\tND_PRINT((ndo,")"));'), (949, '\t\t\t\tgoto trunc;'), (950, '\t\t\t}'), (951, '\t\t}'), (953, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (954, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (955, '\t\t\tND_PRINT((ndo,")"));'), (956, '\t\t\tgoto trunc;'), (957, '\t\t}'), (961, ''), (962, 'trunc:'), (963, '\treturn NULL;'), (967, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)'), (972, '\tND_TCHECK(p[0]);'), (975, '\telse {'), (976, '\t\tND_TCHECK_16BITS(&p[2]);'), (978, '\t}'), (979, '\tif (ep2 < p + totlen) {'), (981, '\t\treturn ep2 + 1;'), (984, '\tND_TCHECK_16BITS(&p[0]);'), (991, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {'), (992, '\t\t\tND_PRINT((ndo,")"));'), (993, '\t\t\tgoto trunc;'), (994, '\t\t}'), (996, '\t\tND_PRINT((ndo,"len=%d value=", totlen - 4));'), (997, '\t\tif (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {'), (998, '\t\t\tND_PRINT((ndo,")"));'), (999, '\t\t\tgoto trunc;'), (1000, '\t\t}'), (1004, ''), (1005, 'trunc:'), (1006, '\treturn NULL;'), (1287, '\t\tif (map && nmap)'), (1288, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1289, '\t\telse'), (1290, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1291, '\t\tif (cp == NULL)'), (1292, '\t\t\tgoto trunc;'), (1756, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1757, '\t\t\t\tif (cp == NULL) {'), (1758, '\t\t\t\t\tND_PRINT((ndo,")"));'), (1759, '\t\t\t\t\tgoto trunc;'), (1760, '\t\t\t\t}'), (1961, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);'), (1963, '\t\t\tcp = ikev1_attr_print(ndo, cp, ep2);'), (1964, '\t\tif (cp == NULL)'), (1965, '\t\t\tgoto trunc;')], 'deleted': [(915, '\t\t const u_char *p, const u_char *ep,'), (923, '\telse'), (925, '\tif (ep < p + totlen) {'), (927, '\t\treturn ep + 1;'), (941, '\t\telse'), (942, '\t\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (944, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (945, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (952, 'ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)'), (959, '\telse'), (961, '\tif (ep < p + totlen) {'), (963, '\t\treturn ep + 1;'), (972, '\t\trawprint(ndo, (const uint8_t *)&p[2], 2);'), (974, '\t\tND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));'), (975, '\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));'), (1259, '\t\tif (map && nmap) {'), (1260, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1261, '\t\t\t\tmap, nmap);'), (1262, '\t\t} else'), (1263, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);'), (1727, '\t\t\t\tcp = ikev1_attrmap_print(ndo, cp,'), (1728, '\t\t\t\t\t(ep < ep2) ? ep : ep2, map, nmap);'), (1929, '\t\t\tcp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,'), (1930, '\t\t\t\tmap, nmap);'), (1932, '\t\t\tcp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);')]}
58
25
2,305
15,204
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13039
['CWE-125']
parse.c
parse_config
/* * This file is part of ubridge, a program to bridge network interfaces * to UDP tunnels. * * Copyright (C) 2015 GNS3 Technologies Inc. * * ubridge is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ubridge 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include "parse.h" #include "nio_udp.h" #include "nio_unix.h" #include "nio_ethernet.h" #include "nio_tap.h" #include "pcap_capture.h" #include "pcap_filter.h" #ifdef LINUX_RAW #include "nio_linux_raw.h" #endif #ifdef __APPLE__ #include "nio_fusion_vmnet.h" #endif static nio_t *create_udp_tunnel(const char *params) { nio_t *nio; char *local_port; char *remote_host; char *remote_port; printf("Creating UDP tunnel %s\n", params); local_port = strtok((char *)params, ":"); remote_host = strtok(NULL, ":"); remote_port = strtok(NULL, ":"); if (local_port == NULL || remote_host == NULL || remote_port == NULL) { fprintf(stderr, "invalid UDP tunnel syntax\n"); return NULL; } nio = create_nio_udp(atoi(local_port), remote_host, atoi(remote_port)); if (!nio) fprintf(stderr, "unable to create UDP NIO\n"); return nio; } static nio_t *create_unix_socket(const char *params) { nio_t *nio; char *local; char *remote; printf("Creating UNIX domain socket %s\n", params); local = strtok((char *)params, ":"); remote = strtok(NULL, ":"); if (local == NULL || remote == NULL) { fprintf(stderr, "invalid UNIX domain socket syntax\n"); return NULL; } nio = create_nio_unix(local, remote); if (!nio) fprintf(stderr, "unable to create UNIX NIO\n"); return nio; } static nio_t *open_ethernet_device(const char *dev_name) { nio_t *nio; printf("Opening Ethernet device %s\n", dev_name); nio = create_nio_ethernet((char *)dev_name); if (!nio) fprintf(stderr, "unable to open Ethernet device\n"); return nio; } static nio_t *open_tap_device(const char *dev_name) { nio_t *nio; printf("Opening TAP device %s\n", dev_name); nio = create_nio_tap((char *)dev_name); if (!nio) fprintf(stderr, "unable to open TAP device\n"); return nio; } #ifdef LINUX_RAW static nio_t *open_linux_raw(const char *dev_name) { nio_t *nio; printf("Opening Linux RAW device %s\n", dev_name); nio = create_nio_linux_raw((char *)dev_name); if (!nio) fprintf(stderr, "unable to open RAW device\n"); return nio; } #endif #ifdef __APPLE__ static nio_t *open_fusion_vmnet(const char *vmnet_name) { nio_t *nio; printf("Opening Fusion VMnet %s\n", vmnet_name); nio = create_nio_fusion_vmnet((char *)vmnet_name); if (!nio) fprintf(stderr, "unable to open Fusion VMnet interface\n"); return nio; } #endif static int getstr(dictionary *ubridge_config, const char *section, const char *entry, const char **value) { char key[MAX_KEY_SIZE]; snprintf(key, MAX_KEY_SIZE, "%s:%s", section, entry); *value = iniparser_getstring(ubridge_config, key, NULL); if (*value) return TRUE; return FALSE; } static bridge_t *add_bridge(bridge_t **head) { bridge_t *bridge; if ((bridge = malloc(sizeof(*bridge))) != NULL) { memset(bridge, 0, sizeof(*bridge)); bridge->next = *head; *head = bridge; } return bridge; } static void parse_capture(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_file = NULL; const char *pcap_linktype = "EN10MB"; getstr(ubridge_config, bridge_name, "pcap_protocol", &pcap_linktype); if (getstr(ubridge_config, bridge_name, "pcap_file", &pcap_file)) { printf("Starting packet capture to %s with protocol %s\n", pcap_file, pcap_linktype); bridge->capture = create_pcap_capture(pcap_file, pcap_linktype); } } static void parse_filter(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_filter = NULL; if (getstr(ubridge_config, bridge_name, "pcap_filter", &pcap_filter)) { printf("Applying PCAP filter '%s'\n", pcap_filter); if (bridge->source_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->source_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to source NIO\n"); } else if (bridge->destination_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->destination_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to destination NIO\n"); } } } int parse_config(char *filename, bridge_t **bridges) { dictionary *ubridge_config = NULL; const char *value; const char *bridge_name; int i, nsec; if ((ubridge_config = iniparser_load(filename)) == NULL) { return FALSE; } nsec = iniparser_getnsec(ubridge_config); for (i = 0; i < nsec; i++) { bridge_t *bridge; nio_t *source_nio = NULL; nio_t *destination_nio = NULL; bridge_name = iniparser_getsecname(ubridge_config, i); printf("Parsing %s\n", bridge_name); if (getstr(ubridge_config, bridge_name, "source_udp", &value)) source_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "source_unix", &value)) source_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "source_ethernet", &value)) source_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "source_tap", &value)) source_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "source_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "source_fusion_vmnet", &value)) source_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "source NIO not found\n"); if (getstr(ubridge_config, bridge_name, "destination_udp", &value)) destination_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "destination_unix", &value)) destination_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "destination_ethernet", &value)) destination_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "destination_tap", &value)) destination_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "destination_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "destination_fusion_vmnet", &value)) destination_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "destination NIO not found\n"); if (source_nio && destination_nio) { bridge = add_bridge(bridges); bridge->source_nio = source_nio; bridge->destination_nio = destination_nio; if (!(bridge->name = strdup(bridge_name))) { fprintf(stderr, "bridge creation: insufficient memory\n"); return FALSE; } parse_capture(ubridge_config, bridge_name, bridge); parse_filter(ubridge_config, bridge_name, bridge); } else if (source_nio != NULL) free_nio(source_nio); else if (destination_nio != NULL) free_nio(destination_nio); } iniparser_freedict(ubridge_config); return TRUE; }
/* * This file is part of ubridge, a program to bridge network interfaces * to UDP tunnels. * * Copyright (C) 2015 GNS3 Technologies Inc. * * ubridge is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ubridge 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include "parse.h" #include "nio_udp.h" #include "nio_unix.h" #include "nio_ethernet.h" #include "nio_tap.h" #include "pcap_capture.h" #include "pcap_filter.h" #ifdef LINUX_RAW #include "nio_linux_raw.h" #endif #ifdef __APPLE__ #include "nio_fusion_vmnet.h" #endif static nio_t *create_udp_tunnel(const char *params) { nio_t *nio; char *local_port; char *remote_host; char *remote_port; printf("Creating UDP tunnel %s\n", params); local_port = strtok((char *)params, ":"); remote_host = strtok(NULL, ":"); remote_port = strtok(NULL, ":"); if (local_port == NULL || remote_host == NULL || remote_port == NULL) { fprintf(stderr, "invalid UDP tunnel syntax\n"); return NULL; } nio = create_nio_udp(atoi(local_port), remote_host, atoi(remote_port)); if (!nio) fprintf(stderr, "unable to create UDP NIO\n"); return nio; } static nio_t *create_unix_socket(const char *params) { nio_t *nio; char *local; char *remote; printf("Creating UNIX domain socket %s\n", params); local = strtok((char *)params, ":"); remote = strtok(NULL, ":"); if (local == NULL || remote == NULL) { fprintf(stderr, "invalid UNIX domain socket syntax\n"); return NULL; } nio = create_nio_unix(local, remote); if (!nio) fprintf(stderr, "unable to create UNIX NIO\n"); return nio; } static nio_t *open_ethernet_device(const char *dev_name) { nio_t *nio; printf("Opening Ethernet device %s\n", dev_name); nio = create_nio_ethernet((char *)dev_name); if (!nio) fprintf(stderr, "unable to open Ethernet device\n"); return nio; } static nio_t *open_tap_device(const char *dev_name) { nio_t *nio; printf("Opening TAP device %s\n", dev_name); nio = create_nio_tap((char *)dev_name); if (!nio) fprintf(stderr, "unable to open TAP device\n"); return nio; } #ifdef LINUX_RAW static nio_t *open_linux_raw(const char *dev_name) { nio_t *nio; printf("Opening Linux RAW device %s\n", dev_name); nio = create_nio_linux_raw((char *)dev_name); if (!nio) fprintf(stderr, "unable to open RAW device\n"); return nio; } #endif #ifdef __APPLE__ static nio_t *open_fusion_vmnet(const char *vmnet_name) { nio_t *nio; printf("Opening Fusion VMnet %s\n", vmnet_name); nio = create_nio_fusion_vmnet((char *)vmnet_name); if (!nio) fprintf(stderr, "unable to open Fusion VMnet interface\n"); return nio; } #endif static int getstr(dictionary *ubridge_config, const char *section, const char *entry, const char **value) { char key[MAX_KEY_SIZE]; snprintf(key, MAX_KEY_SIZE, "%s:%s", section, entry); *value = iniparser_getstring(ubridge_config, key, NULL); if (*value) return TRUE; return FALSE; } static bridge_t *add_bridge(bridge_t **head) { bridge_t *bridge; if ((bridge = malloc(sizeof(*bridge))) != NULL) { memset(bridge, 0, sizeof(*bridge)); bridge->next = *head; *head = bridge; } return bridge; } static void parse_capture(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_file = NULL; const char *pcap_linktype = "EN10MB"; getstr(ubridge_config, bridge_name, "pcap_protocol", &pcap_linktype); if (getstr(ubridge_config, bridge_name, "pcap_file", &pcap_file)) { printf("Starting packet capture to %s with protocol %s\n", pcap_file, pcap_linktype); bridge->capture = create_pcap_capture(pcap_file, pcap_linktype); } } static void parse_filter(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_filter = NULL; if (getstr(ubridge_config, bridge_name, "pcap_filter", &pcap_filter)) { printf("Applying PCAP filter '%s'\n", pcap_filter); if (bridge->source_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->source_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to source NIO\n"); } else if (bridge->destination_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->destination_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to destination NIO\n"); } } } int parse_config(char *filename, bridge_t **bridges) { dictionary *ubridge_config = NULL; const char *value; const char *bridge_name; int i, nsec; if ((ubridge_config = iniparser_load(filename, HIDE_ERRORED_LINE_CONTENT)) == NULL) { return FALSE; } nsec = iniparser_getnsec(ubridge_config); for (i = 0; i < nsec; i++) { bridge_t *bridge; nio_t *source_nio = NULL; nio_t *destination_nio = NULL; bridge_name = iniparser_getsecname(ubridge_config, i); printf("Parsing %s\n", bridge_name); if (getstr(ubridge_config, bridge_name, "source_udp", &value)) source_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "source_unix", &value)) source_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "source_ethernet", &value)) source_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "source_tap", &value)) source_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "source_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "source_fusion_vmnet", &value)) source_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "source NIO not found\n"); if (getstr(ubridge_config, bridge_name, "destination_udp", &value)) destination_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "destination_unix", &value)) destination_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "destination_ethernet", &value)) destination_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "destination_tap", &value)) destination_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "destination_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "destination_fusion_vmnet", &value)) destination_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "destination NIO not found\n"); if (source_nio && destination_nio) { bridge = add_bridge(bridges); bridge->source_nio = source_nio; bridge->destination_nio = destination_nio; if (!(bridge->name = strdup(bridge_name))) { fprintf(stderr, "bridge creation: insufficient memory\n"); return FALSE; } parse_capture(ubridge_config, bridge_name, bridge); parse_filter(ubridge_config, bridge_name, bridge); } else if (source_nio != NULL) free_nio(source_nio); else if (destination_nio != NULL) free_nio(destination_nio); } iniparser_freedict(ubridge_config); return TRUE; }
int parse_config(char *filename, bridge_t **bridges) { dictionary *ubridge_config = NULL; const char *value; const char *bridge_name; int i, nsec; if ((ubridge_config = iniparser_load(filename)) == NULL) { return FALSE; } nsec = iniparser_getnsec(ubridge_config); for (i = 0; i < nsec; i++) { bridge_t *bridge; nio_t *source_nio = NULL; nio_t *destination_nio = NULL; bridge_name = iniparser_getsecname(ubridge_config, i); printf("Parsing %s\n", bridge_name); if (getstr(ubridge_config, bridge_name, "source_udp", &value)) source_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "source_unix", &value)) source_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "source_ethernet", &value)) source_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "source_tap", &value)) source_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "source_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "source_fusion_vmnet", &value)) source_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "source NIO not found\n"); if (getstr(ubridge_config, bridge_name, "destination_udp", &value)) destination_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "destination_unix", &value)) destination_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "destination_ethernet", &value)) destination_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "destination_tap", &value)) destination_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "destination_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "destination_fusion_vmnet", &value)) destination_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "destination NIO not found\n"); if (source_nio && destination_nio) { bridge = add_bridge(bridges); bridge->source_nio = source_nio; bridge->destination_nio = destination_nio; if (!(bridge->name = strdup(bridge_name))) { fprintf(stderr, "bridge creation: insufficient memory\n"); return FALSE; } parse_capture(ubridge_config, bridge_name, bridge); parse_filter(ubridge_config, bridge_name, bridge); } else if (source_nio != NULL) free_nio(source_nio); else if (destination_nio != NULL) free_nio(destination_nio); } iniparser_freedict(ubridge_config); return TRUE; }
int parse_config(char *filename, bridge_t **bridges) { dictionary *ubridge_config = NULL; const char *value; const char *bridge_name; int i, nsec; if ((ubridge_config = iniparser_load(filename, HIDE_ERRORED_LINE_CONTENT)) == NULL) { return FALSE; } nsec = iniparser_getnsec(ubridge_config); for (i = 0; i < nsec; i++) { bridge_t *bridge; nio_t *source_nio = NULL; nio_t *destination_nio = NULL; bridge_name = iniparser_getsecname(ubridge_config, i); printf("Parsing %s\n", bridge_name); if (getstr(ubridge_config, bridge_name, "source_udp", &value)) source_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "source_unix", &value)) source_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "source_ethernet", &value)) source_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "source_tap", &value)) source_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "source_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "source_fusion_vmnet", &value)) source_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "source NIO not found\n"); if (getstr(ubridge_config, bridge_name, "destination_udp", &value)) destination_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "destination_unix", &value)) destination_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "destination_ethernet", &value)) destination_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "destination_tap", &value)) destination_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "destination_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "destination_fusion_vmnet", &value)) destination_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "destination NIO not found\n"); if (source_nio && destination_nio) { bridge = add_bridge(bridges); bridge->source_nio = source_nio; bridge->destination_nio = destination_nio; if (!(bridge->name = strdup(bridge_name))) { fprintf(stderr, "bridge creation: insufficient memory\n"); return FALSE; } parse_capture(ubridge_config, bridge_name, bridge); parse_filter(ubridge_config, bridge_name, bridge); } else if (source_nio != NULL) free_nio(source_nio); else if (destination_nio != NULL) free_nio(destination_nio); } iniparser_freedict(ubridge_config); return TRUE; }
{'added': [(189, ' if ((ubridge_config = iniparser_load(filename, HIDE_ERRORED_LINE_CONTENT)) == NULL) {')], 'deleted': [(189, ' if ((ubridge_config = iniparser_load(filename)) == NULL) {')]}
1
1
190
1,258
https://github.com/GNS3/ubridge
CVE-2020-14976
['CWE-269']
pyfr_driver_asp_reg.c
my_csr_reader
/****************************************************************************** ** Copyright (c) 2014-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. 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. ** ** 3. Neither the name of the copyright holder 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 ** ** HOLDER 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. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <sys/time.h> #define REPS 100 #define REALTYPE double static double sec(struct timeval start, struct timeval end) { return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6; } int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } int main(int argc, char* argv[]) { char* l_csr_file; REALTYPE* l_a_sp; unsigned int* l_rowptr; unsigned int* l_colidx; unsigned int l_rowcount, l_colcount, l_elements; REALTYPE* l_a_dense; REALTYPE* l_b; REALTYPE* l_c_betaone; REALTYPE* l_c_betazero; REALTYPE* l_c_gold_betaone; REALTYPE* l_c_gold_betazero; REALTYPE* l_c_dense_betaone; REALTYPE* l_c_dense_betazero; REALTYPE l_max_error = 0.0; unsigned int l_m; unsigned int l_n; unsigned int l_k; unsigned int l_i; unsigned int l_j; unsigned int l_z; unsigned int l_elems; unsigned int l_reps; unsigned int l_n_block; struct timeval l_start, l_end; double l_total; double alpha = 1.0; double beta = 1.0; char trans = 'N'; libxsmm_dfsspmdm* gemm_op_betazero = NULL; libxsmm_dfsspmdm* gemm_op_betaone = NULL; if (argc != 4 ) { fprintf( stderr, "need csr-filename N reps!\n" ); exit(-1); } /* read sparse A */ l_csr_file = argv[1]; l_n = atoi(argv[2]); l_reps = atoi(argv[3]); if (my_csr_reader( l_csr_file, &l_rowptr, &l_colidx, &l_a_sp, &l_rowcount, &l_colcount, &l_elements ) != 0 ) { exit(-1); } l_m = l_rowcount; l_k = l_colcount; printf("CSR matrix data structure we just read:\n"); printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements); /* allocate dense matrices */ l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64); l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64); l_c_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); /* touch B */ for ( l_i = 0; l_i < l_k*l_n; l_i++) { l_b[l_i] = (REALTYPE)libxsmm_rand_f64(); } /* touch dense A */ for ( l_i = 0; l_i < l_k*l_m; l_i++) { l_a_dense[l_i] = (REALTYPE)0.0; } /* init dense A using sparse A */ for ( l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for ( l_z = 0; l_z < l_elems; l_z++ ) { l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z]; } } /* touch C */ for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betaone[l_i] = (REALTYPE)libxsmm_rand_f64(); } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betazero[l_i] = l_c_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betazero[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betazero[l_i] = l_c_dense_betaone[l_i]; } /* setting up fsspmdm */ l_n_block = 48; beta = 0.0; gemm_op_betazero = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); beta = 1.0; gemm_op_betaone = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); /* compute golden results */ printf("computing golden solution...\n"); for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; l_c_gold_betazero[(l_n*l_i) + l_j] = 0.0; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betazero[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betaone[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } printf("...done!\n"); /* libxsmm generated code */ printf("computing libxsmm (A sparse) solution...\n"); #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } printf("...done!\n"); /* BLAS code */ printf("computing BLAS (A dense) solution...\n"); beta = 0.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); beta = 1.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); printf("...done!\n"); /* check for errors */ l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (dense vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (dense vs. gold): %f\n", l_max_error); /* Let's measure performance */ gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 0.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 1.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); /* free */ libxsmm_dfsspmdm_destroy( gemm_op_betazero ); libxsmm_dfsspmdm_destroy( gemm_op_betaone ); }
/****************************************************************************** ** Copyright (c) 2014-2018, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. 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. ** ** 3. Neither the name of the copyright holder 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 ** ** HOLDER 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. ** ******************************************************************************/ /* Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <sys/time.h> #define REPS 100 #define REALTYPE double static double sec(struct timeval start, struct timeval end) { return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6; } int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } int main(int argc, char* argv[]) { char* l_csr_file; REALTYPE* l_a_sp; unsigned int* l_rowptr; unsigned int* l_colidx; unsigned int l_rowcount, l_colcount, l_elements; REALTYPE* l_a_dense; REALTYPE* l_b; REALTYPE* l_c_betaone; REALTYPE* l_c_betazero; REALTYPE* l_c_gold_betaone; REALTYPE* l_c_gold_betazero; REALTYPE* l_c_dense_betaone; REALTYPE* l_c_dense_betazero; REALTYPE l_max_error = 0.0; unsigned int l_m; unsigned int l_n; unsigned int l_k; unsigned int l_i; unsigned int l_j; unsigned int l_z; unsigned int l_elems; unsigned int l_reps; unsigned int l_n_block; struct timeval l_start, l_end; double l_total; double alpha = 1.0; double beta = 1.0; char trans = 'N'; libxsmm_dfsspmdm* gemm_op_betazero = NULL; libxsmm_dfsspmdm* gemm_op_betaone = NULL; if (argc != 4 ) { fprintf( stderr, "need csr-filename N reps!\n" ); exit(-1); } /* read sparse A */ l_csr_file = argv[1]; l_n = atoi(argv[2]); l_reps = atoi(argv[3]); if (my_csr_reader( l_csr_file, &l_rowptr, &l_colidx, &l_a_sp, &l_rowcount, &l_colcount, &l_elements ) != 0 ) { exit(-1); } l_m = l_rowcount; l_k = l_colcount; printf("CSR matrix data structure we just read:\n"); printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements); /* allocate dense matrices */ l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64); l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64); l_c_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betazero = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense_betaone = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); /* touch B */ for ( l_i = 0; l_i < l_k*l_n; l_i++) { l_b[l_i] = (REALTYPE)libxsmm_rand_f64(); } /* touch dense A */ for ( l_i = 0; l_i < l_k*l_m; l_i++) { l_a_dense[l_i] = (REALTYPE)0.0; } /* init dense A using sparse A */ for ( l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for ( l_z = 0; l_z < l_elems; l_z++ ) { l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z]; } } /* touch C */ for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betaone[l_i] = (REALTYPE)libxsmm_rand_f64(); } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betaone[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_betazero[l_i] = l_c_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_gold_betazero[l_i] = l_c_gold_betaone[l_i]; } for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c_dense_betazero[l_i] = l_c_dense_betaone[l_i]; } /* setting up fsspmdm */ l_n_block = 48; beta = 0.0; gemm_op_betazero = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); beta = 1.0; gemm_op_betaone = libxsmm_dfsspmdm_create( l_m, l_n_block, l_k, l_k, l_n, l_n, 1.0, beta, l_a_dense ); /* compute golden results */ printf("computing golden solution...\n"); for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; l_c_gold_betazero[(l_n*l_i) + l_j] = 0.0; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betazero[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold_betaone[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } printf("...done!\n"); /* libxsmm generated code */ printf("computing libxsmm (A sparse) solution...\n"); #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } printf("...done!\n"); /* BLAS code */ printf("computing BLAS (A dense) solution...\n"); beta = 0.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); beta = 1.0; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); printf("...done!\n"); /* check for errors */ l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betazero[l_i]-l_c_gold_betazero[l_i]); } } printf("max error beta=0 (dense vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense_betaone[l_i]-l_c_gold_betaone[l_i]); } } printf("max error beta=1 (dense vs. gold): %f\n", l_max_error); /* Let's measure performance */ gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betazero, l_b+l_z, l_c_betazero+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { #ifdef _OPENMP #pragma omp parallel for private(l_z) #endif for (l_z = 0; l_z < l_n; l_z+=l_n_block) { libxsmm_dfsspmdm_execute( gemm_op_betaone, l_b+l_z, l_c_betaone+l_z ); } } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 0.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betazero, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=0): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); beta = 1.0; for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense_betaone, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i, beta=1): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); /* free */ libxsmm_dfsspmdm_destroy( gemm_op_betazero ); libxsmm_dfsspmdm_destroy( gemm_op_betaone ); }
int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; }
int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; }
{'added': [(78, ' if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) &&'), (79, ' 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count)'), (80, ' {')], 'deleted': [(78, ' if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {')]}
3
1
296
3,091
https://github.com/hfp/libxsmm
CVE-2018-20541
['CWE-787']
normal.c
nv_replace
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * normal.c: Contains the main routine for processing characters in command * mode. Communicates closely with the code in ops.c to handle * the operators. */ #include "vim.h" static int VIsual_mode_orig = NUL; // saved Visual mode #ifdef FEAT_EVAL static void set_vcount_ca(cmdarg_T *cap, int *set_prevcount); #endif static int nv_compare(const void *s1, const void *s2); static void unshift_special(cmdarg_T *cap); #ifdef FEAT_CMDL_INFO static void del_from_showcmd(int); #endif /* * nv_*(): functions called to handle Normal and Visual mode commands. * n_*(): functions called to handle Normal mode commands. * v_*(): functions called to handle Visual mode commands. */ static void nv_ignore(cmdarg_T *cap); static void nv_nop(cmdarg_T *cap); static void nv_error(cmdarg_T *cap); static void nv_help(cmdarg_T *cap); static void nv_addsub(cmdarg_T *cap); static void nv_page(cmdarg_T *cap); static void nv_zet(cmdarg_T *cap); #ifdef FEAT_GUI static void nv_ver_scrollbar(cmdarg_T *cap); static void nv_hor_scrollbar(cmdarg_T *cap); #endif #ifdef FEAT_GUI_TABLINE static void nv_tabline(cmdarg_T *cap); static void nv_tabmenu(cmdarg_T *cap); #endif static void nv_exmode(cmdarg_T *cap); static void nv_colon(cmdarg_T *cap); static void nv_ctrlg(cmdarg_T *cap); static void nv_ctrlh(cmdarg_T *cap); static void nv_clear(cmdarg_T *cap); static void nv_ctrlo(cmdarg_T *cap); static void nv_hat(cmdarg_T *cap); static void nv_Zet(cmdarg_T *cap); static void nv_ident(cmdarg_T *cap); static void nv_tagpop(cmdarg_T *cap); static void nv_scroll(cmdarg_T *cap); static void nv_right(cmdarg_T *cap); static void nv_left(cmdarg_T *cap); static void nv_up(cmdarg_T *cap); static void nv_down(cmdarg_T *cap); static void nv_end(cmdarg_T *cap); static void nv_dollar(cmdarg_T *cap); static void nv_search(cmdarg_T *cap); static void nv_next(cmdarg_T *cap); static int normal_search(cmdarg_T *cap, int dir, char_u *pat, int opt, int *wrapped); static void nv_csearch(cmdarg_T *cap); static void nv_brackets(cmdarg_T *cap); static void nv_percent(cmdarg_T *cap); static void nv_brace(cmdarg_T *cap); static void nv_mark(cmdarg_T *cap); static void nv_findpar(cmdarg_T *cap); static void nv_undo(cmdarg_T *cap); static void nv_kundo(cmdarg_T *cap); static void nv_Replace(cmdarg_T *cap); static void nv_replace(cmdarg_T *cap); static void nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos); static void v_visop(cmdarg_T *cap); static void nv_subst(cmdarg_T *cap); static void nv_abbrev(cmdarg_T *cap); static void nv_optrans(cmdarg_T *cap); static void nv_gomark(cmdarg_T *cap); static void nv_pcmark(cmdarg_T *cap); static void nv_regname(cmdarg_T *cap); static void nv_visual(cmdarg_T *cap); static void n_start_visual_mode(int c); static void nv_window(cmdarg_T *cap); static void nv_suspend(cmdarg_T *cap); static void nv_g_cmd(cmdarg_T *cap); static void nv_dot(cmdarg_T *cap); static void nv_redo(cmdarg_T *cap); static void nv_Undo(cmdarg_T *cap); static void nv_tilde(cmdarg_T *cap); static void nv_operator(cmdarg_T *cap); #ifdef FEAT_EVAL static void set_op_var(int optype); #endif static void nv_lineop(cmdarg_T *cap); static void nv_home(cmdarg_T *cap); static void nv_pipe(cmdarg_T *cap); static void nv_bck_word(cmdarg_T *cap); static void nv_wordcmd(cmdarg_T *cap); static void nv_beginline(cmdarg_T *cap); static void adjust_cursor(oparg_T *oap); static void adjust_for_sel(cmdarg_T *cap); static void nv_select(cmdarg_T *cap); static void nv_goto(cmdarg_T *cap); static void nv_normal(cmdarg_T *cap); static void nv_esc(cmdarg_T *oap); static void nv_edit(cmdarg_T *cap); static void invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln); #ifdef FEAT_TEXTOBJ static void nv_object(cmdarg_T *cap); #endif static void nv_record(cmdarg_T *cap); static void nv_at(cmdarg_T *cap); static void nv_halfpage(cmdarg_T *cap); static void nv_join(cmdarg_T *cap); static void nv_put(cmdarg_T *cap); static void nv_put_opt(cmdarg_T *cap, int fix_indent); static void nv_open(cmdarg_T *cap); #ifdef FEAT_NETBEANS_INTG static void nv_nbcmd(cmdarg_T *cap); #endif #ifdef FEAT_DND static void nv_drop(cmdarg_T *cap); #endif static void nv_cursorhold(cmdarg_T *cap); static char *e_noident = N_("E349: No identifier under cursor"); /* * Function to be called for a Normal or Visual mode command. * The argument is a cmdarg_T. */ typedef void (*nv_func_T)(cmdarg_T *cap); // Values for cmd_flags. #define NV_NCH 0x01 // may need to get a second char #define NV_NCH_NOP (0x02|NV_NCH) // get second char when no operator pending #define NV_NCH_ALW (0x04|NV_NCH) // always get a second char #define NV_LANG 0x08 // second char needs language adjustment #define NV_SS 0x10 // may start selection #define NV_SSS 0x20 // may start selection with shift modifier #define NV_STS 0x40 // may stop selection without shift modif. #define NV_RL 0x80 // 'rightleft' modifies command #define NV_KEEPREG 0x100 // don't clear regname #define NV_NCW 0x200 // not allowed in command-line window /* * Generally speaking, every Normal mode command should either clear any * pending operator (with *clearop*()), or set the motion type variable * oap->motion_type. * * When a cursor motion command is made, it is marked as being a character or * line oriented motion. Then, if an operator is in effect, the operation * becomes character or line oriented accordingly. */ /* * This table contains one entry for every Normal or Visual mode command. * The order doesn't matter, init_normal_cmds() will create a sorted index. * It is faster when all keys from zero to '~' are present. */ static const struct nv_cmd { int cmd_char; // (first) command character nv_func_T cmd_func; // function for this command short_u cmd_flags; // NV_ flags short cmd_arg; // value for ca.arg } nv_cmds[] = { {NUL, nv_error, 0, 0}, {Ctrl_A, nv_addsub, 0, 0}, {Ctrl_B, nv_page, NV_STS, BACKWARD}, {Ctrl_C, nv_esc, 0, TRUE}, {Ctrl_D, nv_halfpage, 0, 0}, {Ctrl_E, nv_scroll_line, 0, TRUE}, {Ctrl_F, nv_page, NV_STS, FORWARD}, {Ctrl_G, nv_ctrlg, 0, 0}, {Ctrl_H, nv_ctrlh, 0, 0}, {Ctrl_I, nv_pcmark, 0, 0}, {NL, nv_down, 0, FALSE}, {Ctrl_K, nv_error, 0, 0}, {Ctrl_L, nv_clear, 0, 0}, {CAR, nv_down, 0, TRUE}, {Ctrl_N, nv_down, NV_STS, FALSE}, {Ctrl_O, nv_ctrlo, 0, 0}, {Ctrl_P, nv_up, NV_STS, FALSE}, {Ctrl_Q, nv_visual, 0, FALSE}, {Ctrl_R, nv_redo, 0, 0}, {Ctrl_S, nv_ignore, 0, 0}, {Ctrl_T, nv_tagpop, NV_NCW, 0}, {Ctrl_U, nv_halfpage, 0, 0}, {Ctrl_V, nv_visual, 0, FALSE}, {'V', nv_visual, 0, FALSE}, {'v', nv_visual, 0, FALSE}, {Ctrl_W, nv_window, 0, 0}, {Ctrl_X, nv_addsub, 0, 0}, {Ctrl_Y, nv_scroll_line, 0, FALSE}, {Ctrl_Z, nv_suspend, 0, 0}, {ESC, nv_esc, 0, FALSE}, {Ctrl_BSL, nv_normal, NV_NCH_ALW, 0}, {Ctrl_RSB, nv_ident, NV_NCW, 0}, {Ctrl_HAT, nv_hat, NV_NCW, 0}, {Ctrl__, nv_error, 0, 0}, {' ', nv_right, 0, 0}, {'!', nv_operator, 0, 0}, {'"', nv_regname, NV_NCH_NOP|NV_KEEPREG, 0}, {'#', nv_ident, 0, 0}, {'$', nv_dollar, 0, 0}, {'%', nv_percent, 0, 0}, {'&', nv_optrans, 0, 0}, {'\'', nv_gomark, NV_NCH_ALW, TRUE}, {'(', nv_brace, 0, BACKWARD}, {')', nv_brace, 0, FORWARD}, {'*', nv_ident, 0, 0}, {'+', nv_down, 0, TRUE}, {',', nv_csearch, 0, TRUE}, {'-', nv_up, 0, TRUE}, {'.', nv_dot, NV_KEEPREG, 0}, {'/', nv_search, 0, FALSE}, {'0', nv_beginline, 0, 0}, {'1', nv_ignore, 0, 0}, {'2', nv_ignore, 0, 0}, {'3', nv_ignore, 0, 0}, {'4', nv_ignore, 0, 0}, {'5', nv_ignore, 0, 0}, {'6', nv_ignore, 0, 0}, {'7', nv_ignore, 0, 0}, {'8', nv_ignore, 0, 0}, {'9', nv_ignore, 0, 0}, {':', nv_colon, 0, 0}, {';', nv_csearch, 0, FALSE}, {'<', nv_operator, NV_RL, 0}, {'=', nv_operator, 0, 0}, {'>', nv_operator, NV_RL, 0}, {'?', nv_search, 0, FALSE}, {'@', nv_at, NV_NCH_NOP, FALSE}, {'A', nv_edit, 0, 0}, {'B', nv_bck_word, 0, 1}, {'C', nv_abbrev, NV_KEEPREG, 0}, {'D', nv_abbrev, NV_KEEPREG, 0}, {'E', nv_wordcmd, 0, TRUE}, {'F', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD}, {'G', nv_goto, 0, TRUE}, {'H', nv_scroll, 0, 0}, {'I', nv_edit, 0, 0}, {'J', nv_join, 0, 0}, {'K', nv_ident, 0, 0}, {'L', nv_scroll, 0, 0}, {'M', nv_scroll, 0, 0}, {'N', nv_next, 0, SEARCH_REV}, {'O', nv_open, 0, 0}, {'P', nv_put, 0, 0}, {'Q', nv_exmode, NV_NCW, 0}, {'R', nv_Replace, 0, FALSE}, {'S', nv_subst, NV_KEEPREG, 0}, {'T', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD}, {'U', nv_Undo, 0, 0}, {'W', nv_wordcmd, 0, TRUE}, {'X', nv_abbrev, NV_KEEPREG, 0}, {'Y', nv_abbrev, NV_KEEPREG, 0}, {'Z', nv_Zet, NV_NCH_NOP|NV_NCW, 0}, {'[', nv_brackets, NV_NCH_ALW, BACKWARD}, {'\\', nv_error, 0, 0}, {']', nv_brackets, NV_NCH_ALW, FORWARD}, {'^', nv_beginline, 0, BL_WHITE | BL_FIX}, {'_', nv_lineop, 0, 0}, {'`', nv_gomark, NV_NCH_ALW, FALSE}, {'a', nv_edit, NV_NCH, 0}, {'b', nv_bck_word, 0, 0}, {'c', nv_operator, 0, 0}, {'d', nv_operator, 0, 0}, {'e', nv_wordcmd, 0, FALSE}, {'f', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD}, {'g', nv_g_cmd, NV_NCH_ALW, FALSE}, {'h', nv_left, NV_RL, 0}, {'i', nv_edit, NV_NCH, 0}, {'j', nv_down, 0, FALSE}, {'k', nv_up, 0, FALSE}, {'l', nv_right, NV_RL, 0}, {'m', nv_mark, NV_NCH_NOP, 0}, {'n', nv_next, 0, 0}, {'o', nv_open, 0, 0}, {'p', nv_put, 0, 0}, {'q', nv_record, NV_NCH, 0}, {'r', nv_replace, NV_NCH_NOP|NV_LANG, 0}, {'s', nv_subst, NV_KEEPREG, 0}, {'t', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD}, {'u', nv_undo, 0, 0}, {'w', nv_wordcmd, 0, FALSE}, {'x', nv_abbrev, NV_KEEPREG, 0}, {'y', nv_operator, 0, 0}, {'z', nv_zet, NV_NCH_ALW, 0}, {'{', nv_findpar, 0, BACKWARD}, {'|', nv_pipe, 0, 0}, {'}', nv_findpar, 0, FORWARD}, {'~', nv_tilde, 0, 0}, // pound sign {POUND, nv_ident, 0, 0}, {K_MOUSEUP, nv_mousescroll, 0, MSCR_UP}, {K_MOUSEDOWN, nv_mousescroll, 0, MSCR_DOWN}, {K_MOUSELEFT, nv_mousescroll, 0, MSCR_LEFT}, {K_MOUSERIGHT, nv_mousescroll, 0, MSCR_RIGHT}, {K_LEFTMOUSE, nv_mouse, 0, 0}, {K_LEFTMOUSE_NM, nv_mouse, 0, 0}, {K_LEFTDRAG, nv_mouse, 0, 0}, {K_LEFTRELEASE, nv_mouse, 0, 0}, {K_LEFTRELEASE_NM, nv_mouse, 0, 0}, {K_MOUSEMOVE, nv_mouse, 0, 0}, {K_MIDDLEMOUSE, nv_mouse, 0, 0}, {K_MIDDLEDRAG, nv_mouse, 0, 0}, {K_MIDDLERELEASE, nv_mouse, 0, 0}, {K_RIGHTMOUSE, nv_mouse, 0, 0}, {K_RIGHTDRAG, nv_mouse, 0, 0}, {K_RIGHTRELEASE, nv_mouse, 0, 0}, {K_X1MOUSE, nv_mouse, 0, 0}, {K_X1DRAG, nv_mouse, 0, 0}, {K_X1RELEASE, nv_mouse, 0, 0}, {K_X2MOUSE, nv_mouse, 0, 0}, {K_X2DRAG, nv_mouse, 0, 0}, {K_X2RELEASE, nv_mouse, 0, 0}, {K_IGNORE, nv_ignore, NV_KEEPREG, 0}, {K_NOP, nv_nop, 0, 0}, {K_INS, nv_edit, 0, 0}, {K_KINS, nv_edit, 0, 0}, {K_BS, nv_ctrlh, 0, 0}, {K_UP, nv_up, NV_SSS|NV_STS, FALSE}, {K_S_UP, nv_page, NV_SS, BACKWARD}, {K_DOWN, nv_down, NV_SSS|NV_STS, FALSE}, {K_S_DOWN, nv_page, NV_SS, FORWARD}, {K_LEFT, nv_left, NV_SSS|NV_STS|NV_RL, 0}, {K_S_LEFT, nv_bck_word, NV_SS|NV_RL, 0}, {K_C_LEFT, nv_bck_word, NV_SSS|NV_RL|NV_STS, 1}, {K_RIGHT, nv_right, NV_SSS|NV_STS|NV_RL, 0}, {K_S_RIGHT, nv_wordcmd, NV_SS|NV_RL, FALSE}, {K_C_RIGHT, nv_wordcmd, NV_SSS|NV_RL|NV_STS, TRUE}, {K_PAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD}, {K_KPAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD}, {K_PAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD}, {K_KPAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD}, {K_END, nv_end, NV_SSS|NV_STS, FALSE}, {K_KEND, nv_end, NV_SSS|NV_STS, FALSE}, {K_S_END, nv_end, NV_SS, FALSE}, {K_C_END, nv_end, NV_SSS|NV_STS, TRUE}, {K_HOME, nv_home, NV_SSS|NV_STS, 0}, {K_KHOME, nv_home, NV_SSS|NV_STS, 0}, {K_S_HOME, nv_home, NV_SS, 0}, {K_C_HOME, nv_goto, NV_SSS|NV_STS, FALSE}, {K_DEL, nv_abbrev, 0, 0}, {K_KDEL, nv_abbrev, 0, 0}, {K_UNDO, nv_kundo, 0, 0}, {K_HELP, nv_help, NV_NCW, 0}, {K_F1, nv_help, NV_NCW, 0}, {K_XF1, nv_help, NV_NCW, 0}, {K_SELECT, nv_select, 0, 0}, #ifdef FEAT_GUI {K_VER_SCROLLBAR, nv_ver_scrollbar, 0, 0}, {K_HOR_SCROLLBAR, nv_hor_scrollbar, 0, 0}, #endif #ifdef FEAT_GUI_TABLINE {K_TABLINE, nv_tabline, 0, 0}, {K_TABMENU, nv_tabmenu, 0, 0}, #endif #ifdef FEAT_NETBEANS_INTG {K_F21, nv_nbcmd, NV_NCH_ALW, 0}, #endif #ifdef FEAT_DND {K_DROP, nv_drop, NV_STS, 0}, #endif {K_CURSORHOLD, nv_cursorhold, NV_KEEPREG, 0}, {K_PS, nv_edit, 0, 0}, {K_COMMAND, nv_colon, 0, 0}, }; // Number of commands in nv_cmds[]. #define NV_CMDS_SIZE ARRAY_LENGTH(nv_cmds) // Sorted index of commands in nv_cmds[]. static short nv_cmd_idx[NV_CMDS_SIZE]; // The highest index for which // nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char] static int nv_max_linear; /* * Compare functions for qsort() below, that checks the command character * through the index in nv_cmd_idx[]. */ static int nv_compare(const void *s1, const void *s2) { int c1, c2; // The commands are sorted on absolute value. c1 = nv_cmds[*(const short *)s1].cmd_char; c2 = nv_cmds[*(const short *)s2].cmd_char; if (c1 < 0) c1 = -c1; if (c2 < 0) c2 = -c2; return c1 - c2; } /* * Initialize the nv_cmd_idx[] table. */ void init_normal_cmds(void) { int i; // Fill the index table with a one to one relation. for (i = 0; i < (int)NV_CMDS_SIZE; ++i) nv_cmd_idx[i] = i; // Sort the commands by the command character. qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare); // Find the first entry that can't be indexed by the command character. for (i = 0; i < (int)NV_CMDS_SIZE; ++i) if (i != nv_cmds[nv_cmd_idx[i]].cmd_char) break; nv_max_linear = i - 1; } /* * Search for a command in the commands table. * Returns -1 for invalid command. */ static int find_command(int cmdchar) { int i; int idx; int top, bot; int c; // A multi-byte character is never a command. if (cmdchar >= 0x100) return -1; // We use the absolute value of the character. Special keys have a // negative value, but are sorted on their absolute value. if (cmdchar < 0) cmdchar = -cmdchar; // If the character is in the first part: The character is the index into // nv_cmd_idx[]. if (cmdchar <= nv_max_linear) return nv_cmd_idx[cmdchar]; // Perform a binary search. bot = nv_max_linear + 1; top = NV_CMDS_SIZE - 1; idx = -1; while (bot <= top) { i = (top + bot) / 2; c = nv_cmds[nv_cmd_idx[i]].cmd_char; if (c < 0) c = -c; if (cmdchar == c) { idx = nv_cmd_idx[i]; break; } if (cmdchar > c) bot = i + 1; else top = i - 1; } return idx; } /* * Execute a command in Normal mode. */ void normal_cmd( oparg_T *oap, int toplevel UNUSED) // TRUE when called from main() { cmdarg_T ca; // command arguments int c; int ctrl_w = FALSE; // got CTRL-W command int old_col = curwin->w_curswant; #ifdef FEAT_CMDL_INFO int need_flushbuf; // need to call out_flush() #endif pos_T old_pos; // cursor position before command int mapped_len; static int old_mapped_len = 0; int idx; #ifdef FEAT_EVAL int set_prevcount = FALSE; #endif int save_did_cursorhold = did_cursorhold; CLEAR_FIELD(ca); // also resets ca.retval ca.oap = oap; // Use a count remembered from before entering an operator. After typing // "3d" we return from normal_cmd() and come back here, the "3" is // remembered in "opcount". ca.opcount = opcount; /* * If there is an operator pending, then the command we take this time * will terminate it. Finish_op tells us to finish the operation before * returning this time (unless the operation was cancelled). */ #ifdef CURSOR_SHAPE c = finish_op; #endif finish_op = (oap->op_type != OP_NOP); #ifdef CURSOR_SHAPE if (finish_op != c) { ui_cursor_shape(); // may show different cursor shape # ifdef FEAT_MOUSESHAPE update_mouseshape(-1); # endif } #endif // When not finishing an operator and no register name typed, reset the // count. if (!finish_op && !oap->regname) { ca.opcount = 0; #ifdef FEAT_EVAL set_prevcount = TRUE; #endif } // Restore counts from before receiving K_CURSORHOLD. This means after // typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not // "3 * 2". if (oap->prev_opcount > 0 || oap->prev_count0 > 0) { ca.opcount = oap->prev_opcount; ca.count0 = oap->prev_count0; oap->prev_opcount = 0; oap->prev_count0 = 0; } mapped_len = typebuf_maplen(); State = NORMAL_BUSY; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif #ifdef FEAT_EVAL // Set v:count here, when called from main() and not a stuffed // command, so that v:count can be used in an expression mapping // when there is no count. Do set it for redo. if (toplevel && readbuf1_empty()) set_vcount_ca(&ca, &set_prevcount); #endif /* * Get the command character from the user. */ c = safe_vgetc(); LANGMAP_ADJUST(c, get_real_state() != SELECTMODE); /* * If a mapping was started in Visual or Select mode, remember the length * of the mapping. This is used below to not return to Insert mode for as * long as the mapping is being executed. */ if (restart_edit == 0) old_mapped_len = 0; else if (old_mapped_len || (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0)) old_mapped_len = typebuf_maplen(); if (c == NUL) c = K_ZERO; /* * In Select mode, typed text replaces the selection. */ if (VIsual_active && VIsual_select && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER)) { // Fake a "c"hange command. When "restart_edit" is set (e.g., because // 'insertmode' is set) fake a "d"elete command, Insert mode will // restart automatically. // Insert the typed character in the typeahead buffer, so that it can // be mapped in Insert mode. Required for ":lmap" to work. ins_char_typebuf(vgetc_char, vgetc_mod_mask); if (restart_edit != 0) c = 'd'; else c = 'c'; msg_nowait = TRUE; // don't delay going to insert mode old_mapped_len = 0; // do go to Insert mode } #ifdef FEAT_CMDL_INFO need_flushbuf = add_to_showcmd(c); #endif getcount: if (!(VIsual_active && VIsual_select)) { /* * Handle a count before a command and compute ca.count0. * Note that '0' is a command and not the start of a count, but it's * part of a count after other digits. */ while ( (c >= '1' && c <= '9') || (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0'))) { if (c == K_DEL || c == K_KDEL) { ca.count0 /= 10; #ifdef FEAT_CMDL_INFO del_from_showcmd(4); // delete the digit and ~@% #endif } else ca.count0 = ca.count0 * 10 + (c - '0'); if (ca.count0 < 0) // overflow ca.count0 = 999999999L; #ifdef FEAT_EVAL // Set v:count here, when called from main() and not a stuffed // command, so that v:count can be used in an expression mapping // right after the count. Do set it for redo. if (toplevel && readbuf1_empty()) set_vcount_ca(&ca, &set_prevcount); #endif if (ctrl_w) { ++no_mapping; ++allow_keys; // no mapping for nchar, but keys } ++no_zero_mapping; // don't map zero here c = plain_vgetc(); LANGMAP_ADJUST(c, TRUE); --no_zero_mapping; if (ctrl_w) { --no_mapping; --allow_keys; } #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(c); #endif } /* * If we got CTRL-W there may be a/another count */ if (c == Ctrl_W && !ctrl_w && oap->op_type == OP_NOP) { ctrl_w = TRUE; ca.opcount = ca.count0; // remember first count ca.count0 = 0; ++no_mapping; ++allow_keys; // no mapping for nchar, but keys c = plain_vgetc(); // get next character LANGMAP_ADJUST(c, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(c); #endif goto getcount; // jump back } } if (c == K_CURSORHOLD) { // Save the count values so that ca.opcount and ca.count0 are exactly // the same when coming back here after handling K_CURSORHOLD. oap->prev_opcount = ca.opcount; oap->prev_count0 = ca.count0; } else if (ca.opcount != 0) { /* * If we're in the middle of an operator (including after entering a * yank buffer with '"') AND we had a count before the operator, then * that count overrides the current value of ca.count0. * What this means effectively, is that commands like "3dw" get turned * into "d3w" which makes things fall into place pretty neatly. * If you give a count before AND after the operator, they are * multiplied. */ if (ca.count0) ca.count0 *= ca.opcount; else ca.count0 = ca.opcount; if (ca.count0 < 0) // overflow ca.count0 = 999999999L; } /* * Always remember the count. It will be set to zero (on the next call, * above) when there is no pending operator. * When called from main(), save the count for use by the "count" built-in * variable. */ ca.opcount = ca.count0; ca.count1 = (ca.count0 == 0 ? 1 : ca.count0); #ifdef FEAT_EVAL /* * Only set v:count when called from main() and not a stuffed command. * Do set it for redo. */ if (toplevel && readbuf1_empty()) set_vcount(ca.count0, ca.count1, set_prevcount); #endif /* * Find the command character in the table of commands. * For CTRL-W we already got nchar when looking for a count. */ if (ctrl_w) { ca.nchar = c; ca.cmdchar = Ctrl_W; } else ca.cmdchar = c; idx = find_command(ca.cmdchar); if (idx < 0) { // Not a known command: beep. clearopbeep(oap); goto normal_end; } if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW)) { // This command is not allowed while editing a cmdline: beep. clearopbeep(oap); text_locked_msg(); goto normal_end; } if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked()) goto normal_end; /* * In Visual/Select mode, a few keys are handled in a special way. */ if (VIsual_active) { // when 'keymodel' contains "stopsel" may stop Select/Visual mode if (km_stopsel && (nv_cmds[idx].cmd_flags & NV_STS) && !(mod_mask & MOD_MASK_SHIFT)) { end_visual_mode(); redraw_curbuf_later(INVERTED); } // Keys that work different when 'keymodel' contains "startsel" if (km_startsel) { if (nv_cmds[idx].cmd_flags & NV_SS) { unshift_special(&ca); idx = find_command(ca.cmdchar); if (idx < 0) { // Just in case clearopbeep(oap); goto normal_end; } } else if ((nv_cmds[idx].cmd_flags & NV_SSS) && (mod_mask & MOD_MASK_SHIFT)) mod_mask &= ~MOD_MASK_SHIFT; } } #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl && KeyTyped && !KeyStuffed && (nv_cmds[idx].cmd_flags & NV_RL)) { // Invert horizontal movements and operations. Only when typed by the // user directly, not when the result of a mapping or "x" translated // to "dl". switch (ca.cmdchar) { case 'l': ca.cmdchar = 'h'; break; case K_RIGHT: ca.cmdchar = K_LEFT; break; case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break; case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break; case 'h': ca.cmdchar = 'l'; break; case K_LEFT: ca.cmdchar = K_RIGHT; break; case K_S_LEFT: ca.cmdchar = K_S_RIGHT; break; case K_C_LEFT: ca.cmdchar = K_C_RIGHT; break; case '>': ca.cmdchar = '<'; break; case '<': ca.cmdchar = '>'; break; } idx = find_command(ca.cmdchar); } #endif /* * Get an additional character if we need one. */ if ((nv_cmds[idx].cmd_flags & NV_NCH) && (((nv_cmds[idx].cmd_flags & NV_NCH_NOP) == NV_NCH_NOP && oap->op_type == OP_NOP) || (nv_cmds[idx].cmd_flags & NV_NCH_ALW) == NV_NCH_ALW || (ca.cmdchar == 'q' && oap->op_type == OP_NOP && reg_recording == 0 && reg_executing == 0) || ((ca.cmdchar == 'a' || ca.cmdchar == 'i') && (oap->op_type != OP_NOP || VIsual_active)))) { int *cp; int repl = FALSE; // get character for replace mode int lit = FALSE; // get extra character literally int langmap_active = FALSE; // using :lmap mappings int lang; // getting a text character #ifdef HAVE_INPUT_METHOD int save_smd; // saved value of p_smd #endif ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes // Don't generate a CursorHold event here, most commands can't handle // it, e.g., nv_replace(), nv_csearch(). did_cursorhold = TRUE; if (ca.cmdchar == 'g') { /* * For 'g' get the next character now, so that we can check for * "gr", "g'" and "g`". */ ca.nchar = plain_vgetc(); LANGMAP_ADJUST(ca.nchar, TRUE); #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(ca.nchar); #endif if (ca.nchar == 'r' || ca.nchar == '\'' || ca.nchar == '`' || ca.nchar == Ctrl_BSL) { cp = &ca.extra_char; // need to get a third character if (ca.nchar != 'r') lit = TRUE; // get it literally else repl = TRUE; // get it in replace mode } else cp = NULL; // no third character needed } else { if (ca.cmdchar == 'r') // get it in replace mode repl = TRUE; cp = &ca.nchar; } lang = (repl || (nv_cmds[idx].cmd_flags & NV_LANG)); /* * Get a second or third character. */ if (cp != NULL) { if (repl) { State = REPLACE; // pretend Replace mode #ifdef CURSOR_SHAPE ui_cursor_shape(); // show different cursor shape #endif } if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP) { // Allow mappings defined with ":lmap". --no_mapping; --allow_keys; if (repl) State = LREPLACE; else State = LANGMAP; langmap_active = TRUE; } #ifdef HAVE_INPUT_METHOD save_smd = p_smd; p_smd = FALSE; // Don't let the IM code show the mode here if (lang && curbuf->b_p_iminsert == B_IMODE_IM) im_set_active(TRUE); #endif if ((State & INSERT) && !p_ek) { #ifdef FEAT_JOB_CHANNEL ch_log_output = TRUE; #endif // Disable bracketed paste and modifyOtherKeys here, we won't // recognize the escape sequences with 'esckeys' off. out_str(T_BD); out_str(T_CTE); } *cp = plain_vgetc(); if ((State & INSERT) && !p_ek) { #ifdef FEAT_JOB_CHANNEL ch_log_output = TRUE; #endif // Re-enable bracketed paste mode and modifyOtherKeys out_str(T_BE); out_str(T_CTI); } if (langmap_active) { // Undo the decrement done above ++no_mapping; ++allow_keys; State = NORMAL_BUSY; } #ifdef HAVE_INPUT_METHOD if (lang) { if (curbuf->b_p_iminsert != B_IMODE_LMAP) im_save_status(&curbuf->b_p_iminsert); im_set_active(FALSE); } p_smd = save_smd; #endif State = NORMAL_BUSY; #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(*cp); #endif if (!lit) { #ifdef FEAT_DIGRAPHS // Typing CTRL-K gets a digraph. if (*cp == Ctrl_K && ((nv_cmds[idx].cmd_flags & NV_LANG) || cp == &ca.extra_char) && vim_strchr(p_cpo, CPO_DIGRAPH) == NULL) { c = get_digraph(FALSE); if (c > 0) { *cp = c; # ifdef FEAT_CMDL_INFO // Guessing how to update showcmd here... del_from_showcmd(3); need_flushbuf |= add_to_showcmd(*cp); # endif } } #endif // adjust chars > 127, except after "tTfFr" commands LANGMAP_ADJUST(*cp, !lang); #ifdef FEAT_RIGHTLEFT // adjust Hebrew mapped char if (p_hkmap && lang && KeyTyped) *cp = hkmap(*cp); #endif } /* * When the next character is CTRL-\ a following CTRL-N means the * command is aborted and we go to Normal mode. */ if (cp == &ca.extra_char && ca.nchar == Ctrl_BSL && (ca.extra_char == Ctrl_N || ca.extra_char == Ctrl_G)) { ca.cmdchar = Ctrl_BSL; ca.nchar = ca.extra_char; idx = find_command(ca.cmdchar); } else if ((ca.nchar == 'n' || ca.nchar == 'N') && ca.cmdchar == 'g') ca.oap->op_type = get_op_type(*cp, NUL); else if (*cp == Ctrl_BSL) { long towait = (p_ttm >= 0 ? p_ttm : p_tm); // There is a busy wait here when typing "f<C-\>" and then // something different from CTRL-N. Can't be avoided. while ((c = vpeekc()) <= 0 && towait > 0L) { do_sleep(towait > 50L ? 50L : towait, FALSE); towait -= 50L; } if (c > 0) { c = plain_vgetc(); if (c != Ctrl_N && c != Ctrl_G) vungetc(c); else { ca.cmdchar = Ctrl_BSL; ca.nchar = c; idx = find_command(ca.cmdchar); } } } // When getting a text character and the next character is a // multi-byte character, it could be a composing character. // However, don't wait for it to arrive. Also, do enable mapping, // because if it's put back with vungetc() it's too late to apply // mapping. --no_mapping; while (enc_utf8 && lang && (c = vpeekc()) > 0 && (c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1)) { c = plain_vgetc(); if (!utf_iscomposing(c)) { vungetc(c); // it wasn't, put it back break; } else if (ca.ncharC1 == 0) ca.ncharC1 = c; else ca.ncharC2 = c; } ++no_mapping; } --no_mapping; --allow_keys; } #ifdef FEAT_CMDL_INFO /* * Flush the showcmd characters onto the screen so we can see them while * the command is being executed. Only do this when the shown command was * actually displayed, otherwise this will slow down a lot when executing * mappings. */ if (need_flushbuf) out_flush(); #endif if (ca.cmdchar != K_IGNORE) { if (ex_normal_busy) did_cursorhold = save_did_cursorhold; else did_cursorhold = FALSE; } State = NORMAL; if (ca.nchar == ESC) { clearop(oap); if (restart_edit == 0 && goto_im()) restart_edit = 'a'; goto normal_end; } if (ca.cmdchar != K_IGNORE) { msg_didout = FALSE; // don't scroll screen up for normal command msg_col = 0; } old_pos = curwin->w_cursor; // remember where cursor was // When 'keymodel' contains "startsel" some keys start Select/Visual // mode. if (!VIsual_active && km_startsel) { if (nv_cmds[idx].cmd_flags & NV_SS) { start_selection(); unshift_special(&ca); idx = find_command(ca.cmdchar); } else if ((nv_cmds[idx].cmd_flags & NV_SSS) && (mod_mask & MOD_MASK_SHIFT)) { start_selection(); mod_mask &= ~MOD_MASK_SHIFT; } } /* * Execute the command! * Call the command function found in the commands table. */ ca.arg = nv_cmds[idx].cmd_arg; (nv_cmds[idx].cmd_func)(&ca); /* * If we didn't start or finish an operator, reset oap->regname, unless we * need it later. */ if (!finish_op && !oap->op_type && (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG))) { clearop(oap); #ifdef FEAT_EVAL reset_reg_var(); #endif } // Get the length of mapped chars again after typing a count, second // character or "z333<cr>". if (old_mapped_len > 0) old_mapped_len = typebuf_maplen(); /* * If an operation is pending, handle it. But not for K_IGNORE or * K_MOUSEMOVE. */ if (ca.cmdchar != K_IGNORE && ca.cmdchar != K_MOUSEMOVE) do_pending_operator(&ca, old_col, FALSE); /* * Wait for a moment when a message is displayed that will be overwritten * by the mode message. * In Visual mode and with "^O" in Insert mode, a short message will be * overwritten by the mode message. Wait a bit, until a key is hit. * In Visual mode, it's more important to keep the Visual area updated * than keeping a message (e.g. from a /pat search). * Only do this if the command was typed, not from a mapping. * Don't wait when emsg_silent is non-zero. * Also wait a bit after an error message, e.g. for "^O:". * Don't redraw the screen, it would remove the message. */ if ( ((p_smd && msg_silent == 0 && (restart_edit != 0 || (VIsual_active && old_pos.lnum == curwin->w_cursor.lnum && old_pos.col == curwin->w_cursor.col) ) && (clear_cmdline || redraw_cmdline) && (msg_didout || (msg_didany && msg_scroll)) && !msg_nowait && KeyTyped) || (restart_edit != 0 && !VIsual_active && (msg_scroll || emsg_on_display))) && oap->regname == 0 && !(ca.retval & CA_COMMAND_BUSY) && stuff_empty() && typebuf_typed() && emsg_silent == 0 && !in_assert_fails && !did_wait_return && oap->op_type == OP_NOP) { int save_State = State; // Draw the cursor with the right shape here if (restart_edit != 0) State = INSERT; // If need to redraw, and there is a "keep_msg", redraw before the // delay if (must_redraw && keep_msg != NULL && !emsg_on_display) { char_u *kmsg; kmsg = keep_msg; keep_msg = NULL; // Showmode() will clear keep_msg, but we want to use it anyway. // First update w_topline. setcursor(); update_screen(0); // now reset it, otherwise it's put in the history again keep_msg = kmsg; kmsg = vim_strsave(keep_msg); if (kmsg != NULL) { msg_attr((char *)kmsg, keep_msg_attr); vim_free(kmsg); } } setcursor(); #ifdef CURSOR_SHAPE ui_cursor_shape(); // may show different cursor shape #endif cursor_on(); out_flush(); if (msg_scroll || emsg_on_display) ui_delay(1003L, TRUE); // wait at least one second ui_delay(3003L, FALSE); // wait up to three seconds State = save_State; msg_scroll = FALSE; emsg_on_display = FALSE; } /* * Finish up after executing a Normal mode command. */ normal_end: msg_nowait = FALSE; #ifdef FEAT_EVAL if (finish_op) reset_reg_var(); #endif // Reset finish_op, in case it was set #ifdef CURSOR_SHAPE c = finish_op; #endif finish_op = FALSE; #ifdef CURSOR_SHAPE // Redraw the cursor with another shape, if we were in Operator-pending // mode or did a replace command. if (c || ca.cmdchar == 'r') { ui_cursor_shape(); // may show different cursor shape # ifdef FEAT_MOUSESHAPE update_mouseshape(-1); # endif } #endif #ifdef FEAT_CMDL_INFO if (oap->op_type == OP_NOP && oap->regname == 0 && ca.cmdchar != K_CURSORHOLD) clear_showcmd(); #endif checkpcmark(); // check if we moved since setting pcmark vim_free(ca.searchbuf); if (has_mbyte) mb_adjust_cursor(); if (curwin->w_p_scb && toplevel) { validate_cursor(); // may need to update w_leftcol do_check_scrollbind(TRUE); } if (curwin->w_p_crb && toplevel) { validate_cursor(); // may need to update w_leftcol do_check_cursorbind(); } #ifdef FEAT_TERMINAL // don't go to Insert mode if a terminal has a running job if (term_job_running(curbuf->b_term)) restart_edit = 0; #endif /* * May restart edit(), if we got here with CTRL-O in Insert mode (but not * if still inside a mapping that started in Visual mode). * May switch from Visual to Select mode after CTRL-O command. */ if ( oap->op_type == OP_NOP && ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0) || restart_VIsual_select == 1) && !(ca.retval & CA_COMMAND_BUSY) && stuff_empty() && oap->regname == 0) { if (restart_VIsual_select == 1) { VIsual_select = TRUE; showmode(); restart_VIsual_select = 0; } if (restart_edit != 0 && !VIsual_active && old_mapped_len == 0) (void)edit(restart_edit, FALSE, 1L); } if (restart_VIsual_select == 2) restart_VIsual_select = 1; // Save count before an operator for next time. opcount = ca.opcount; } #ifdef FEAT_EVAL /* * Set v:count and v:count1 according to "cap". * Set v:prevcount only when "set_prevcount" is TRUE. */ static void set_vcount_ca(cmdarg_T *cap, int *set_prevcount) { long count = cap->count0; // multiply with cap->opcount the same way as above if (cap->opcount != 0) count = cap->opcount * (count == 0 ? 1 : count); set_vcount(count, count == 0 ? 1 : count, *set_prevcount); *set_prevcount = FALSE; // only set v:prevcount once } #endif /* * Check if highlighting for Visual mode is possible, give a warning message * if not. */ void check_visual_highlight(void) { static int did_check = FALSE; if (full_screen) { if (!did_check && HL_ATTR(HLF_V) == 0) msg(_("Warning: terminal cannot highlight")); did_check = TRUE; } } #if defined(FEAT_CLIPBOARD) && defined(FEAT_EVAL) /* * Call yank_do_autocmd() for "regname". */ static void call_yank_do_autocmd(int regname) { oparg_T oa; yankreg_T *reg; clear_oparg(&oa); oa.regname = regname; oa.op_type = OP_YANK; oa.is_VIsual = TRUE; reg = get_register(regname, TRUE); yank_do_autocmd(&oa, reg); free_register(reg); } #endif /* * End Visual mode. * This function or the next should ALWAYS be called to end Visual mode, except * from do_pending_operator(). */ void end_visual_mode() { end_visual_mode_keep_button(); reset_held_button(); } void end_visual_mode_keep_button() { #ifdef FEAT_CLIPBOARD /* * If we are using the clipboard, then remember what was selected in case * we need to paste it somewhere while we still own the selection. * Only do this when the clipboard is already owned. Don't want to grab * the selection when hitting ESC. */ if (clip_star.available && clip_star.owned) clip_auto_select(); # if defined(FEAT_EVAL) // Emit a TextYankPost for the automatic copy of the selection into the // star and/or plus register. if (has_textyankpost()) { if (clip_isautosel_star()) call_yank_do_autocmd('*'); if (clip_isautosel_plus()) call_yank_do_autocmd('+'); } # endif #endif VIsual_active = FALSE; setmouse(); mouse_dragging = 0; // Save the current VIsual area for '< and '> marks, and "gv" curbuf->b_visual.vi_mode = VIsual_mode; curbuf->b_visual.vi_start = VIsual; curbuf->b_visual.vi_end = curwin->w_cursor; curbuf->b_visual.vi_curswant = curwin->w_curswant; #ifdef FEAT_EVAL curbuf->b_visual_mode_eval = VIsual_mode; #endif if (!virtual_active()) curwin->w_cursor.coladd = 0; may_clear_cmdline(); adjust_cursor_eol(); } /* * Reset VIsual_active and VIsual_reselect. */ void reset_VIsual_and_resel(void) { if (VIsual_active) { end_visual_mode(); redraw_curbuf_later(INVERTED); // delete the inversion later } VIsual_reselect = FALSE; } /* * Reset VIsual_active and VIsual_reselect if it's set. */ void reset_VIsual(void) { if (VIsual_active) { end_visual_mode(); redraw_curbuf_later(INVERTED); // delete the inversion later VIsual_reselect = FALSE; } } void restore_visual_mode(void) { if (VIsual_mode_orig != NUL) { curbuf->b_visual.vi_mode = VIsual_mode_orig; VIsual_mode_orig = NUL; } } /* * Check for a balloon-eval special item to include when searching for an * identifier. When "dir" is BACKWARD "ptr[-1]" must be valid! * Returns TRUE if the character at "*ptr" should be included. * "dir" is FORWARD or BACKWARD, the direction of searching. * "*colp" is in/decremented if "ptr[-dir]" should also be included. * "bnp" points to a counter for square brackets. */ static int find_is_eval_item( char_u *ptr, int *colp, int *bnp, int dir) { // Accept everything inside []. if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD)) ++*bnp; if (*bnp > 0) { if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD)) --*bnp; return TRUE; } // skip over "s.var" if (*ptr == '.') return TRUE; // two-character item: s->var if (ptr[dir == BACKWARD ? 0 : 1] == '>' && ptr[dir == BACKWARD ? -1 : 0] == '-') { *colp += dir; return TRUE; } return FALSE; } /* * Find the identifier under or to the right of the cursor. * "find_type" can have one of three values: * FIND_IDENT: find an identifier (keyword) * FIND_STRING: find any non-white text * FIND_IDENT + FIND_STRING: find any non-white text, identifier preferred. * FIND_EVAL: find text useful for C program debugging * * There are three steps: * 1. Search forward for the start of an identifier/text. Doesn't move if * already on one. * 2. Search backward for the start of this identifier/text. * This doesn't match the real Vi but I like it a little better and it * shouldn't bother anyone. * 3. Search forward to the end of this identifier/text. * When FIND_IDENT isn't defined, we backup until a blank. * * Returns the length of the text, or zero if no text is found. * If text is found, a pointer to the text is put in "*text". This * points into the current buffer line and is not always NUL terminated. */ int find_ident_under_cursor(char_u **text, int find_type) { return find_ident_at_pos(curwin, curwin->w_cursor.lnum, curwin->w_cursor.col, text, NULL, find_type); } /* * Like find_ident_under_cursor(), but for any window and any position. * However: Uses 'iskeyword' from the current window!. */ int find_ident_at_pos( win_T *wp, linenr_T lnum, colnr_T startcol, char_u **text, int *textcol, // column where "text" starts, can be NULL int find_type) { char_u *ptr; int col = 0; // init to shut up GCC int i; int this_class = 0; int prev_class; int prevcol; int bn = 0; // bracket nesting /* * if i == 0: try to find an identifier * if i == 1: try to find any non-white text */ ptr = ml_get_buf(wp->w_buffer, lnum, FALSE); for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; ++i) { /* * 1. skip to start of identifier/text */ col = startcol; if (has_mbyte) { while (ptr[col] != NUL) { // Stop at a ']' to evaluate "a[x]". if ((find_type & FIND_EVAL) && ptr[col] == ']') break; this_class = mb_get_class(ptr + col); if (this_class != 0 && (i == 1 || this_class != 1)) break; col += (*mb_ptr2len)(ptr + col); } } else while (ptr[col] != NUL && (i == 0 ? !vim_iswordc(ptr[col]) : VIM_ISWHITE(ptr[col])) && (!(find_type & FIND_EVAL) || ptr[col] != ']') ) ++col; // When starting on a ']' count it, so that we include the '['. bn = ptr[col] == ']'; /* * 2. Back up to start of identifier/text. */ if (has_mbyte) { // Remember class of character under cursor. if ((find_type & FIND_EVAL) && ptr[col] == ']') this_class = mb_get_class((char_u *)"a"); else this_class = mb_get_class(ptr + col); while (col > 0 && this_class != 0) { prevcol = col - 1 - (*mb_head_off)(ptr, ptr + col - 1); prev_class = mb_get_class(ptr + prevcol); if (this_class != prev_class && (i == 0 || prev_class == 0 || (find_type & FIND_IDENT)) && (!(find_type & FIND_EVAL) || prevcol == 0 || !find_is_eval_item(ptr + prevcol, &prevcol, &bn, BACKWARD)) ) break; col = prevcol; } // If we don't want just any old text, or we've found an // identifier, stop searching. if (this_class > 2) this_class = 2; if (!(find_type & FIND_STRING) || this_class == 2) break; } else { while (col > 0 && ((i == 0 ? vim_iswordc(ptr[col - 1]) : (!VIM_ISWHITE(ptr[col - 1]) && (!(find_type & FIND_IDENT) || !vim_iswordc(ptr[col - 1])))) || ((find_type & FIND_EVAL) && col > 1 && find_is_eval_item(ptr + col - 1, &col, &bn, BACKWARD)) )) --col; // If we don't want just any old text, or we've found an // identifier, stop searching. if (!(find_type & FIND_STRING) || vim_iswordc(ptr[col])) break; } } if (ptr[col] == NUL || (i == 0 && (has_mbyte ? this_class != 2 : !vim_iswordc(ptr[col])))) { // didn't find an identifier or text if ((find_type & FIND_NOERROR) == 0) { if (find_type & FIND_STRING) emsg(_("E348: No string under cursor")); else emsg(_(e_noident)); } return 0; } ptr += col; *text = ptr; if (textcol != NULL) *textcol = col; /* * 3. Find the end if the identifier/text. */ bn = 0; startcol -= col; col = 0; if (has_mbyte) { // Search for point of changing multibyte character class. this_class = mb_get_class(ptr); while (ptr[col] != NUL && ((i == 0 ? mb_get_class(ptr + col) == this_class : mb_get_class(ptr + col) != 0) || ((find_type & FIND_EVAL) && col <= (int)startcol && find_is_eval_item(ptr + col, &col, &bn, FORWARD)) )) col += (*mb_ptr2len)(ptr + col); } else while ((i == 0 ? vim_iswordc(ptr[col]) : (ptr[col] != NUL && !VIM_ISWHITE(ptr[col]))) || ((find_type & FIND_EVAL) && col <= (int)startcol && find_is_eval_item(ptr + col, &col, &bn, FORWARD)) ) ++col; return col; } /* * Prepare for redo of a normal command. */ static void prep_redo_cmd(cmdarg_T *cap) { prep_redo(cap->oap->regname, cap->count0, NUL, cap->cmdchar, NUL, NUL, cap->nchar); } /* * Prepare for redo of any command. * Note that only the last argument can be a multi-byte char. */ void prep_redo( int regname, long num, int cmd1, int cmd2, int cmd3, int cmd4, int cmd5) { ResetRedobuff(); if (regname != 0) // yank from specified buffer { AppendCharToRedobuff('"'); AppendCharToRedobuff(regname); } if (num) AppendNumberToRedobuff(num); if (cmd1 != NUL) AppendCharToRedobuff(cmd1); if (cmd2 != NUL) AppendCharToRedobuff(cmd2); if (cmd3 != NUL) AppendCharToRedobuff(cmd3); if (cmd4 != NUL) AppendCharToRedobuff(cmd4); if (cmd5 != NUL) AppendCharToRedobuff(cmd5); } /* * check for operator active and clear it * * return TRUE if operator was active */ static int checkclearop(oparg_T *oap) { if (oap->op_type == OP_NOP) return FALSE; clearopbeep(oap); return TRUE; } /* * Check for operator or Visual active. Clear active operator. * * Return TRUE if operator or Visual was active. */ static int checkclearopq(oparg_T *oap) { if (oap->op_type == OP_NOP && !VIsual_active) return FALSE; clearopbeep(oap); return TRUE; } void clearop(oparg_T *oap) { oap->op_type = OP_NOP; oap->regname = 0; oap->motion_force = NUL; oap->use_reg_one = FALSE; motion_force = NUL; } void clearopbeep(oparg_T *oap) { clearop(oap); beep_flush(); } /* * Remove the shift modifier from a special key. */ static void unshift_special(cmdarg_T *cap) { switch (cap->cmdchar) { case K_S_RIGHT: cap->cmdchar = K_RIGHT; break; case K_S_LEFT: cap->cmdchar = K_LEFT; break; case K_S_UP: cap->cmdchar = K_UP; break; case K_S_DOWN: cap->cmdchar = K_DOWN; break; case K_S_HOME: cap->cmdchar = K_HOME; break; case K_S_END: cap->cmdchar = K_END; break; } cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask); } /* * If the mode is currently displayed clear the command line or update the * command displayed. */ void may_clear_cmdline(void) { if (mode_displayed) clear_cmdline = TRUE; // unshow visual mode later #ifdef FEAT_CMDL_INFO else clear_showcmd(); #endif } #if defined(FEAT_CMDL_INFO) || defined(PROTO) /* * Routines for displaying a partly typed command */ #define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30 static char_u showcmd_buf[SHOWCMD_BUFLEN]; static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; // For push_showcmd() static int showcmd_is_clear = TRUE; static int showcmd_visual = FALSE; static void display_showcmd(void); void clear_showcmd(void) { if (!p_sc) return; if (VIsual_active && !char_avail()) { int cursor_bot = LT_POS(VIsual, curwin->w_cursor); long lines; colnr_T leftcol, rightcol; linenr_T top, bot; // Show the size of the Visual area. if (cursor_bot) { top = VIsual.lnum; bot = curwin->w_cursor.lnum; } else { top = curwin->w_cursor.lnum; bot = VIsual.lnum; } # ifdef FEAT_FOLDING // Include closed folds as a whole. (void)hasFolding(top, &top, NULL); (void)hasFolding(bot, NULL, &bot); # endif lines = bot - top + 1; if (VIsual_mode == Ctrl_V) { # ifdef FEAT_LINEBREAK char_u *saved_sbr = p_sbr; char_u *saved_w_sbr = curwin->w_p_sbr; // Make 'sbr' empty for a moment to get the correct size. p_sbr = empty_option; curwin->w_p_sbr = empty_option; # endif getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol); # ifdef FEAT_LINEBREAK p_sbr = saved_sbr; curwin->w_p_sbr = saved_w_sbr; # endif sprintf((char *)showcmd_buf, "%ldx%ld", lines, (long)(rightcol - leftcol + 1)); } else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum) sprintf((char *)showcmd_buf, "%ld", lines); else { char_u *s, *e; int l; int bytes = 0; int chars = 0; if (cursor_bot) { s = ml_get_pos(&VIsual); e = ml_get_cursor(); } else { s = ml_get_cursor(); e = ml_get_pos(&VIsual); } while ((*p_sel != 'e') ? s <= e : s < e) { l = (*mb_ptr2len)(s); if (l == 0) { ++bytes; ++chars; break; // end of line } bytes += l; ++chars; s += l; } if (bytes == chars) sprintf((char *)showcmd_buf, "%d", chars); else sprintf((char *)showcmd_buf, "%d-%d", chars, bytes); } showcmd_buf[SHOWCMD_COLS] = NUL; // truncate showcmd_visual = TRUE; } else { showcmd_buf[0] = NUL; showcmd_visual = FALSE; // Don't actually display something if there is nothing to clear. if (showcmd_is_clear) return; } display_showcmd(); } /* * Add 'c' to string of shown command chars. * Return TRUE if output has been written (and setcursor() has been called). */ int add_to_showcmd(int c) { char_u *p; int old_len; int extra_len; int overflow; int i; static int ignore[] = { #ifdef FEAT_GUI K_VER_SCROLLBAR, K_HOR_SCROLLBAR, K_LEFTMOUSE_NM, K_LEFTRELEASE_NM, #endif K_IGNORE, K_PS, K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE, K_MOUSEMOVE, K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE, K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE, K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT, K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE, K_CURSORHOLD, 0 }; if (!p_sc || msg_silent != 0) return FALSE; if (showcmd_visual) { showcmd_buf[0] = NUL; showcmd_visual = FALSE; } // Ignore keys that are scrollbar updates and mouse clicks if (IS_SPECIAL(c)) for (i = 0; ignore[i] != 0; ++i) if (ignore[i] == c) return FALSE; p = transchar(c); if (*p == ' ') STRCPY(p, "<20>"); old_len = (int)STRLEN(showcmd_buf); extra_len = (int)STRLEN(p); overflow = old_len + extra_len - SHOWCMD_COLS; if (overflow > 0) mch_memmove(showcmd_buf, showcmd_buf + overflow, old_len - overflow + 1); STRCAT(showcmd_buf, p); if (char_avail()) return FALSE; display_showcmd(); return TRUE; } void add_to_showcmd_c(int c) { if (!add_to_showcmd(c)) setcursor(); } /* * Delete 'len' characters from the end of the shown command. */ static void del_from_showcmd(int len) { int old_len; if (!p_sc) return; old_len = (int)STRLEN(showcmd_buf); if (len > old_len) len = old_len; showcmd_buf[old_len - len] = NUL; if (!char_avail()) display_showcmd(); } /* * push_showcmd() and pop_showcmd() are used when waiting for the user to type * something and there is a partial mapping. */ void push_showcmd(void) { if (p_sc) STRCPY(old_showcmd_buf, showcmd_buf); } void pop_showcmd(void) { if (!p_sc) return; STRCPY(showcmd_buf, old_showcmd_buf); display_showcmd(); } static void display_showcmd(void) { int len; cursor_off(); len = (int)STRLEN(showcmd_buf); if (len == 0) showcmd_is_clear = TRUE; else { screen_puts(showcmd_buf, (int)Rows - 1, sc_col, 0); showcmd_is_clear = FALSE; } /* * clear the rest of an old message by outputting up to SHOWCMD_COLS * spaces */ screen_puts((char_u *)" " + len, (int)Rows - 1, sc_col + len, 0); setcursor(); // put cursor back where it belongs } #endif /* * When "check" is FALSE, prepare for commands that scroll the window. * When "check" is TRUE, take care of scroll-binding after the window has * scrolled. Called from normal_cmd() and edit(). */ void do_check_scrollbind(int check) { static win_T *old_curwin = NULL; static linenr_T old_topline = 0; #ifdef FEAT_DIFF static int old_topfill = 0; #endif static buf_T *old_buf = NULL; static colnr_T old_leftcol = 0; if (check && curwin->w_p_scb) { // If a ":syncbind" command was just used, don't scroll, only reset // the values. if (did_syncbind) did_syncbind = FALSE; else if (curwin == old_curwin) { /* * Synchronize other windows, as necessary according to * 'scrollbind'. Don't do this after an ":edit" command, except * when 'diff' is set. */ if ((curwin->w_buffer == old_buf #ifdef FEAT_DIFF || curwin->w_p_diff #endif ) && (curwin->w_topline != old_topline #ifdef FEAT_DIFF || curwin->w_topfill != old_topfill #endif || curwin->w_leftcol != old_leftcol)) { check_scrollbind(curwin->w_topline - old_topline, (long)(curwin->w_leftcol - old_leftcol)); } } else if (vim_strchr(p_sbo, 'j')) // jump flag set in 'scrollopt' { /* * When switching between windows, make sure that the relative * vertical offset is valid for the new window. The relative * offset is invalid whenever another 'scrollbind' window has * scrolled to a point that would force the current window to * scroll past the beginning or end of its buffer. When the * resync is performed, some of the other 'scrollbind' windows may * need to jump so that the current window's relative position is * visible on-screen. */ check_scrollbind(curwin->w_topline - curwin->w_scbind_pos, 0L); } curwin->w_scbind_pos = curwin->w_topline; } old_curwin = curwin; old_topline = curwin->w_topline; #ifdef FEAT_DIFF old_topfill = curwin->w_topfill; #endif old_buf = curwin->w_buffer; old_leftcol = curwin->w_leftcol; } /* * Synchronize any windows that have "scrollbind" set, based on the * number of rows by which the current window has changed * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>) */ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) { int want_ver; int want_hor; win_T *old_curwin = curwin; buf_T *old_curbuf = curbuf; int old_VIsual_select = VIsual_select; int old_VIsual_active = VIsual_active; colnr_T tgt_leftcol = curwin->w_leftcol; long topline; long y; /* * check 'scrollopt' string for vertical and horizontal scroll options */ want_ver = (vim_strchr(p_sbo, 'v') && topline_diff != 0); #ifdef FEAT_DIFF want_ver |= old_curwin->w_p_diff; #endif want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || topline_diff != 0)); /* * loop through the scrollbound windows and scroll accordingly */ VIsual_select = VIsual_active = 0; FOR_ALL_WINDOWS(curwin) { curbuf = curwin->w_buffer; // skip original window and windows with 'noscrollbind' if (curwin != old_curwin && curwin->w_p_scb) { /* * do the vertical scroll */ if (want_ver) { #ifdef FEAT_DIFF if (old_curwin->w_p_diff && curwin->w_p_diff) { diff_set_topline(old_curwin, curwin); } else #endif { curwin->w_scbind_pos += topline_diff; topline = curwin->w_scbind_pos; if (topline > curbuf->b_ml.ml_line_count) topline = curbuf->b_ml.ml_line_count; if (topline < 1) topline = 1; y = topline - curwin->w_topline; if (y > 0) scrollup(y, FALSE); else scrolldown(-y, FALSE); } redraw_later(VALID); cursor_correct(); curwin->w_redr_status = TRUE; } /* * do the horizontal scroll */ if (want_hor && curwin->w_leftcol != tgt_leftcol) { curwin->w_leftcol = tgt_leftcol; leftcol_changed(); } } } /* * reset current-window */ VIsual_select = old_VIsual_select; VIsual_active = old_VIsual_active; curwin = old_curwin; curbuf = old_curbuf; } /* * Command character that's ignored. * Used for CTRL-Q and CTRL-S to avoid problems with terminals that use * xon/xoff. */ static void nv_ignore(cmdarg_T *cap) { cap->retval |= CA_COMMAND_BUSY; // don't call edit() now } /* * Command character that doesn't do anything, but unlike nv_ignore() does * start edit(). Used for "startinsert" executed while starting up. */ static void nv_nop(cmdarg_T *cap UNUSED) { } /* * Command character doesn't exist. */ static void nv_error(cmdarg_T *cap) { clearopbeep(cap->oap); } /* * <Help> and <F1> commands. */ static void nv_help(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) ex_help(NULL); } /* * CTRL-A and CTRL-X: Add or subtract from letter or number under cursor. */ static void nv_addsub(cmdarg_T *cap) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) clearopbeep(cap->oap); else #endif if (!VIsual_active && cap->oap->op_type == OP_NOP) { prep_redo_cmd(cap); cap->oap->op_type = cap->cmdchar == Ctrl_A ? OP_NR_ADD : OP_NR_SUB; op_addsub(cap->oap, cap->count1, cap->arg); cap->oap->op_type = OP_NOP; } else if (VIsual_active) nv_operator(cap); else clearop(cap->oap); } /* * CTRL-F, CTRL-B, etc: Scroll page up or down. */ static void nv_page(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { if (mod_mask & MOD_MASK_CTRL) { // <C-PageUp>: tab page back; <C-PageDown>: tab page forward if (cap->arg == BACKWARD) goto_tabpage(-(int)cap->count1); else goto_tabpage((int)cap->count0); } else (void)onepage(cap->arg, cap->count1); } } /* * Implementation of "gd" and "gD" command. */ static void nv_gd( oparg_T *oap, int nchar, int thisblock) // 1 for "1gd" and "1gD" { int len; char_u *ptr; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0 || find_decl(ptr, len, nchar == 'd', thisblock, SEARCH_START) == FAIL) clearopbeep(oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_SEARCH) && KeyTyped && oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Return TRUE if line[offset] is not inside a C-style comment or string, FALSE * otherwise. */ static int is_ident(char_u *line, int offset) { int i; int incomment = FALSE; int instring = 0; int prev = 0; for (i = 0; i < offset && line[i] != NUL; i++) { if (instring != 0) { if (prev != '\\' && line[i] == instring) instring = 0; } else if ((line[i] == '"' || line[i] == '\'') && !incomment) { instring = line[i]; } else { if (incomment) { if (prev == '*' && line[i] == '/') incomment = FALSE; } else if (prev == '/' && line[i] == '*') { incomment = TRUE; } else if (prev == '/' && line[i] == '/') { return FALSE; } } prev = line[i]; } return incomment == FALSE && instring == 0; } /* * Search for variable declaration of "ptr[len]". * When "locally" is TRUE in the current function ("gd"), otherwise in the * current file ("gD"). * When "thisblock" is TRUE check the {} block scope. * Return FAIL when not found. */ int find_decl( char_u *ptr, int len, int locally, int thisblock, int flags_arg) // flags passed to searchit() { char_u *pat; pos_T old_pos; pos_T par_pos; pos_T found_pos; int t; int save_p_ws; int save_p_scs; int retval = OK; int incll; int searchflags = flags_arg; int valid; if ((pat = alloc(len + 7)) == NULL) return FAIL; // Put "\V" before the pattern to avoid that the special meaning of "." // and "~" causes trouble. sprintf((char *)pat, vim_iswordp(ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s", len, ptr); old_pos = curwin->w_cursor; save_p_ws = p_ws; save_p_scs = p_scs; p_ws = FALSE; // don't wrap around end of file now p_scs = FALSE; // don't switch ignorecase off now /* * With "gD" go to line 1. * With "gd" Search back for the start of the current function, then go * back until a blank line. If this fails go to line 1. */ if (!locally || !findpar(&incll, BACKWARD, 1L, '{', FALSE)) { setpcmark(); // Set in findpar() otherwise curwin->w_cursor.lnum = 1; par_pos = curwin->w_cursor; } else { par_pos = curwin->w_cursor; while (curwin->w_cursor.lnum > 1 && *skipwhite(ml_get_curline()) != NUL) --curwin->w_cursor.lnum; } curwin->w_cursor.col = 0; // Search forward for the identifier, ignore comment lines. CLEAR_POS(&found_pos); for (;;) { t = searchit(curwin, curbuf, &curwin->w_cursor, NULL, FORWARD, pat, 1L, searchflags, RE_LAST, NULL); if (curwin->w_cursor.lnum >= old_pos.lnum) t = FAIL; // match after start is failure too if (thisblock && t != FAIL) { pos_T *pos; // Check that the block the match is in doesn't end before the // position where we started the search from. if ((pos = findmatchlimit(NULL, '}', FM_FORWARD, (int)(old_pos.lnum - curwin->w_cursor.lnum + 1))) != NULL && pos->lnum < old_pos.lnum) { // There can't be a useful match before the end of this block. // Skip to the end. curwin->w_cursor = *pos; continue; } } if (t == FAIL) { // If we previously found a valid position, use it. if (found_pos.lnum != 0) { curwin->w_cursor = found_pos; t = OK; } break; } if (get_leader_len(ml_get_curline(), NULL, FALSE, TRUE) > 0) { // Ignore this line, continue at start of next line. ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; continue; } valid = is_ident(ml_get_curline(), curwin->w_cursor.col); // If the current position is not a valid identifier and a previous // match is present, favor that one instead. if (!valid && found_pos.lnum != 0) { curwin->w_cursor = found_pos; break; } // Global search: use first valid match found if (valid && !locally) break; if (valid && curwin->w_cursor.lnum >= par_pos.lnum) { // If we previously found a valid position, use it. if (found_pos.lnum != 0) curwin->w_cursor = found_pos; break; } // For finding a local variable and the match is before the "{" or // inside a comment, continue searching. For K&R style function // declarations this skips the function header without types. if (!valid) CLEAR_POS(&found_pos); else found_pos = curwin->w_cursor; // Remove SEARCH_START from flags to avoid getting stuck at one // position. searchflags &= ~SEARCH_START; } if (t == FAIL) { retval = FAIL; curwin->w_cursor = old_pos; } else { curwin->w_set_curswant = TRUE; // "n" searches forward now reset_search_dir(); } vim_free(pat); p_ws = save_p_ws; p_scs = save_p_scs; return retval; } /* * Move 'dist' lines in direction 'dir', counting lines by *screen* * lines rather than lines in the file. * 'dist' must be positive. * * Return OK if able to move cursor, FAIL otherwise. */ static int nv_screengo(oparg_T *oap, int dir, long dist) { int linelen = linetabsize(ml_get_curline()); int retval = OK; int atend = FALSE; int n; int col_off1; // margin offset for first screen line int col_off2; // margin offset for wrapped screen line int width1; // text width for first screen line int width2; // test width for wrapped screen line oap->motion_type = MCHAR; oap->inclusive = (curwin->w_curswant == MAXCOL); col_off1 = curwin_col_off(); col_off2 = col_off1 - curwin_col_off2(); width1 = curwin->w_width - col_off1; width2 = curwin->w_width - col_off2; if (width2 == 0) width2 = 1; // avoid divide by zero if (curwin->w_width != 0) { /* * Instead of sticking at the last character of the buffer line we * try to stick in the last column of the screen. */ if (curwin->w_curswant == MAXCOL) { atend = TRUE; validate_virtcol(); if (width1 <= 0) curwin->w_curswant = 0; else { curwin->w_curswant = width1 - 1; if (curwin->w_virtcol > curwin->w_curswant) curwin->w_curswant += ((curwin->w_virtcol - curwin->w_curswant - 1) / width2 + 1) * width2; } } else { if (linelen > width1) n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; else n = width1; if (curwin->w_curswant >= (colnr_T)n) curwin->w_curswant = n - 1; } while (dist--) { if (dir == BACKWARD) { if ((long)curwin->w_curswant >= width1 #ifdef FEAT_FOLDING && !hasFolding(curwin->w_cursor.lnum, NULL, NULL) #endif ) // Move back within the line. This can give a negative value // for w_curswant if width1 < width2 (with cpoptions+=n), // which will get clipped to column 0. curwin->w_curswant -= width2; else { // to previous line #ifdef FEAT_FOLDING // Move to the start of a closed fold. Don't do that when // 'foldopen' contains "all": it will open in a moment. if (!(fdo_flags & FDO_ALL)) (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); #endif if (curwin->w_cursor.lnum == 1) { retval = FAIL; break; } --curwin->w_cursor.lnum; linelen = linetabsize(ml_get_curline()); if (linelen > width1) curwin->w_curswant += (((linelen - width1 - 1) / width2) + 1) * width2; } } else // dir == FORWARD { if (linelen > width1) n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; else n = width1; if (curwin->w_curswant + width2 < (colnr_T)n #ifdef FEAT_FOLDING && !hasFolding(curwin->w_cursor.lnum, NULL, NULL) #endif ) // move forward within line curwin->w_curswant += width2; else { // to next line #ifdef FEAT_FOLDING // Move to the end of a closed fold. (void)hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum); #endif if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { retval = FAIL; break; } curwin->w_cursor.lnum++; curwin->w_curswant %= width2; // Check if the cursor has moved below the number display // when width1 < width2 (with cpoptions+=n). Subtract width2 // to get a negative value for w_curswant, which will get // clipped to column 0. if (curwin->w_curswant >= width1) curwin->w_curswant -= width2; linelen = linetabsize(ml_get_curline()); } } } } if (virtual_active() && atend) coladvance(MAXCOL); else coladvance(curwin->w_curswant); if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { colnr_T virtcol; /* * Check for landing on a character that got split at the end of the * last line. We want to advance a screenline, not end up in the same * screenline or move two screenlines. */ validate_virtcol(); virtcol = curwin->w_virtcol; #if defined(FEAT_LINEBREAK) if (virtcol > (colnr_T)width1 && *get_showbreak_value(curwin) != NUL) virtcol -= vim_strsize(get_showbreak_value(curwin)); #endif if (virtcol > curwin->w_curswant && (curwin->w_curswant < (colnr_T)width1 ? (curwin->w_curswant > (colnr_T)width1 / 2) : ((curwin->w_curswant - width1) % width2 > (colnr_T)width2 / 2))) --curwin->w_cursor.col; } if (atend) curwin->w_curswant = MAXCOL; // stick in the last column return retval; } /* * Handle CTRL-E and CTRL-Y commands: scroll a line up or down. * cap->arg must be TRUE for CTRL-E. */ void nv_scroll_line(cmdarg_T *cap) { if (!checkclearop(cap->oap)) scroll_redraw(cap->arg, cap->count1); } /* * Scroll "count" lines up or down, and redraw. */ void scroll_redraw(int up, long count) { linenr_T prev_topline = curwin->w_topline; #ifdef FEAT_DIFF int prev_topfill = curwin->w_topfill; #endif linenr_T prev_lnum = curwin->w_cursor.lnum; if (up) scrollup(count, TRUE); else scrolldown(count, TRUE); if (get_scrolloff_value()) { // Adjust the cursor position for 'scrolloff'. Mark w_topline as // valid, otherwise the screen jumps back at the end of the file. cursor_correct(); check_cursor_moved(curwin); curwin->w_valid |= VALID_TOPLINE; // If moved back to where we were, at least move the cursor, otherwise // we get stuck at one position. Don't move the cursor up if the // first line of the buffer is already on the screen while (curwin->w_topline == prev_topline #ifdef FEAT_DIFF && curwin->w_topfill == prev_topfill #endif ) { if (up) { if (curwin->w_cursor.lnum > prev_lnum || cursor_down(1L, FALSE) == FAIL) break; } else { if (curwin->w_cursor.lnum < prev_lnum || prev_topline == 1L || cursor_up(1L, FALSE) == FAIL) break; } // Mark w_topline as valid, otherwise the screen jumps back at the // end of the file. check_cursor_moved(curwin); curwin->w_valid |= VALID_TOPLINE; } } if (curwin->w_cursor.lnum != prev_lnum) coladvance(curwin->w_curswant); redraw_later(VALID); } /* * Commands that start with "z". */ static void nv_zet(cmdarg_T *cap) { long n; colnr_T col; int nchar = cap->nchar; #ifdef FEAT_FOLDING long old_fdl = curwin->w_p_fdl; int old_fen = curwin->w_p_fen; #endif #ifdef FEAT_SPELL int undo = FALSE; #endif long siso = get_sidescrolloff_value(); if (VIM_ISDIGIT(nchar)) { /* * "z123{nchar}": edit the count before obtaining {nchar} */ if (checkclearop(cap->oap)) return; n = nchar - '0'; for (;;) { #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; // disallow scrolling here #endif ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes nchar = plain_vgetc(); LANGMAP_ADJUST(nchar, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO (void)add_to_showcmd(nchar); #endif if (nchar == K_DEL || nchar == K_KDEL) n /= 10; else if (VIM_ISDIGIT(nchar)) n = n * 10 + (nchar - '0'); else if (nchar == CAR) { #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight((int)n); break; } else if (nchar == 'l' || nchar == 'h' || nchar == K_LEFT || nchar == K_RIGHT) { cap->count1 = n ? n * cap->count1 : cap->count1; goto dozet; } else { clearopbeep(cap->oap); break; } } cap->oap->op_type = OP_NOP; return; } dozet: if ( #ifdef FEAT_FOLDING // "zf" and "zF" are always an operator, "zd", "zo", "zO", "zc" // and "zC" only in Visual mode. "zj" and "zk" are motion // commands. cap->nchar != 'f' && cap->nchar != 'F' && !(VIsual_active && vim_strchr((char_u *)"dcCoO", cap->nchar)) && cap->nchar != 'j' && cap->nchar != 'k' && #endif checkclearop(cap->oap)) return; /* * For "z+", "z<CR>", "zt", "z.", "zz", "z^", "z-", "zb": * If line number given, set cursor. */ if ((vim_strchr((char_u *)"+\r\nt.z^-b", nchar) != NULL) && cap->count0 && cap->count0 != curwin->w_cursor.lnum) { setpcmark(); if (cap->count0 > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; else curwin->w_cursor.lnum = cap->count0; check_cursor_col(); } switch (nchar) { // "z+", "z<CR>" and "zt": put cursor at top of screen case '+': if (cap->count0 == 0) { // No count given: put cursor at the line below screen validate_botline(); // make sure w_botline is valid if (curwin->w_botline > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; else curwin->w_cursor.lnum = curwin->w_botline; } // FALLTHROUGH case NL: case CAR: case K_KENTER: beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 't': scroll_cursor_top(0, TRUE); redraw_later(VALID); set_fraction(curwin); break; // "z." and "zz": put cursor in middle of screen case '.': beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 'z': scroll_cursor_halfway(TRUE); redraw_later(VALID); set_fraction(curwin); break; // "z^", "z-" and "zb": put cursor at bottom of screen case '^': // Strange Vi behavior: <count>z^ finds line at top of window // when <count> is at bottom of window, and puts that one at // bottom of window. if (cap->count0 != 0) { scroll_cursor_bot(0, TRUE); curwin->w_cursor.lnum = curwin->w_topline; } else if (curwin->w_topline == 1) curwin->w_cursor.lnum = 1; else curwin->w_cursor.lnum = curwin->w_topline - 1; // FALLTHROUGH case '-': beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 'b': scroll_cursor_bot(0, TRUE); redraw_later(VALID); set_fraction(curwin); break; // "zH" - scroll screen right half-page case 'H': cap->count1 *= curwin->w_width / 2; // FALLTHROUGH // "zh" - scroll screen to the right case 'h': case K_LEFT: if (!curwin->w_p_wrap) { if ((colnr_T)cap->count1 > curwin->w_leftcol) curwin->w_leftcol = 0; else curwin->w_leftcol -= (colnr_T)cap->count1; leftcol_changed(); } break; // "zL" - scroll screen left half-page case 'L': cap->count1 *= curwin->w_width / 2; // FALLTHROUGH // "zl" - scroll screen to the left case 'l': case K_RIGHT: if (!curwin->w_p_wrap) { // scroll the window left curwin->w_leftcol += (colnr_T)cap->count1; leftcol_changed(); } break; // "zs" - scroll screen, cursor at the start case 's': if (!curwin->w_p_wrap) { #ifdef FEAT_FOLDING if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) col = 0; // like the cursor is in col 0 else #endif getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL); if ((long)col > siso) col -= siso; else col = 0; if (curwin->w_leftcol != col) { curwin->w_leftcol = col; redraw_later(NOT_VALID); } } break; // "ze" - scroll screen, cursor at the end case 'e': if (!curwin->w_p_wrap) { #ifdef FEAT_FOLDING if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) col = 0; // like the cursor is in col 0 else #endif getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col); n = curwin->w_width - curwin_col_off(); if ((long)col + siso < n) col = 0; else col = col + siso - n + 1; if (curwin->w_leftcol != col) { curwin->w_leftcol = col; redraw_later(NOT_VALID); } } break; // "zp", "zP" in block mode put without addind trailing spaces case 'P': case 'p': nv_put(cap); break; // "zy" Yank without trailing spaces case 'y': nv_operator(cap); break; #ifdef FEAT_FOLDING // "zF": create fold command // "zf": create fold operator case 'F': case 'f': if (foldManualAllowed(TRUE)) { cap->nchar = 'f'; nv_operator(cap); curwin->w_p_fen = TRUE; // "zF" is like "zfzf" if (nchar == 'F' && cap->oap->op_type == OP_FOLD) { nv_operator(cap); finish_op = TRUE; } } else clearopbeep(cap->oap); break; // "zd": delete fold at cursor // "zD": delete fold at cursor recursively case 'd': case 'D': if (foldManualAllowed(FALSE)) { if (VIsual_active) nv_operator(cap); else deleteFold(curwin->w_cursor.lnum, curwin->w_cursor.lnum, nchar == 'D', FALSE); } break; // "zE": erase all folds case 'E': if (foldmethodIsManual(curwin)) { clearFolding(curwin); changed_window_setting(); } else if (foldmethodIsMarker(curwin)) deleteFold((linenr_T)1, curbuf->b_ml.ml_line_count, TRUE, FALSE); else emsg(_("E352: Cannot erase folds with current 'foldmethod'")); break; // "zn": fold none: reset 'foldenable' case 'n': curwin->w_p_fen = FALSE; break; // "zN": fold Normal: set 'foldenable' case 'N': curwin->w_p_fen = TRUE; break; // "zi": invert folding: toggle 'foldenable' case 'i': curwin->w_p_fen = !curwin->w_p_fen; break; // "za": open closed fold or close open fold at cursor case 'a': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) openFold(curwin->w_cursor.lnum, cap->count1); else { closeFold(curwin->w_cursor.lnum, cap->count1); curwin->w_p_fen = TRUE; } break; // "zA": open fold at cursor recursively case 'A': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) openFoldRecurse(curwin->w_cursor.lnum); else { closeFoldRecurse(curwin->w_cursor.lnum); curwin->w_p_fen = TRUE; } break; // "zo": open fold at cursor or Visual area case 'o': if (VIsual_active) nv_operator(cap); else openFold(curwin->w_cursor.lnum, cap->count1); break; // "zO": open fold recursively case 'O': if (VIsual_active) nv_operator(cap); else openFoldRecurse(curwin->w_cursor.lnum); break; // "zc": close fold at cursor or Visual area case 'c': if (VIsual_active) nv_operator(cap); else closeFold(curwin->w_cursor.lnum, cap->count1); curwin->w_p_fen = TRUE; break; // "zC": close fold recursively case 'C': if (VIsual_active) nv_operator(cap); else closeFoldRecurse(curwin->w_cursor.lnum); curwin->w_p_fen = TRUE; break; // "zv": open folds at the cursor case 'v': foldOpenCursor(); break; // "zx": re-apply 'foldlevel' and open folds at the cursor case 'x': curwin->w_p_fen = TRUE; curwin->w_foldinvalid = TRUE; // recompute folds newFoldLevel(); // update right now foldOpenCursor(); break; // "zX": undo manual opens/closes, re-apply 'foldlevel' case 'X': curwin->w_p_fen = TRUE; curwin->w_foldinvalid = TRUE; // recompute folds old_fdl = -1; // force an update break; // "zm": fold more case 'm': if (curwin->w_p_fdl > 0) { curwin->w_p_fdl -= cap->count1; if (curwin->w_p_fdl < 0) curwin->w_p_fdl = 0; } old_fdl = -1; // force an update curwin->w_p_fen = TRUE; break; // "zM": close all folds case 'M': curwin->w_p_fdl = 0; old_fdl = -1; // force an update curwin->w_p_fen = TRUE; break; // "zr": reduce folding case 'r': curwin->w_p_fdl += cap->count1; { int d = getDeepestNesting(); if (curwin->w_p_fdl >= d) curwin->w_p_fdl = d; } break; // "zR": open all folds case 'R': curwin->w_p_fdl = getDeepestNesting(); old_fdl = -1; // force an update break; case 'j': // "zj" move to next fold downwards case 'k': // "zk" move to next fold upwards if (foldMoveTo(TRUE, nchar == 'j' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); break; #endif // FEAT_FOLDING #ifdef FEAT_SPELL case 'u': // "zug" and "zuw": undo "zg" and "zw" ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes nchar = plain_vgetc(); LANGMAP_ADJUST(nchar, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO (void)add_to_showcmd(nchar); #endif if (vim_strchr((char_u *)"gGwW", nchar) == NULL) { clearopbeep(cap->oap); break; } undo = TRUE; // FALLTHROUGH case 'g': // "zg": add good word to word list case 'w': // "zw": add wrong word to word list case 'G': // "zG": add good word to temp word list case 'W': // "zW": add wrong word to temp word list { char_u *ptr = NULL; int len; if (checkclearop(cap->oap)) break; if (VIsual_active && get_visual_text(cap, &ptr, &len) == FAIL) return; if (ptr == NULL) { pos_T pos = curwin->w_cursor; // Find bad word under the cursor. When 'spell' is // off this fails and find_ident_under_cursor() is // used below. emsg_off++; len = spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL); emsg_off--; if (len != 0 && curwin->w_cursor.col <= pos.col) ptr = ml_get_pos(&curwin->w_cursor); curwin->w_cursor = pos; } if (ptr == NULL && (len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) return; spell_add_word(ptr, len, nchar == 'w' || nchar == 'W' ? SPELL_ADD_BAD : SPELL_ADD_GOOD, (nchar == 'G' || nchar == 'W') ? 0 : (int)cap->count1, undo); } break; case '=': // "z=": suggestions for a badly spelled word if (!checkclearop(cap->oap)) spell_suggest((int)cap->count0); break; #endif default: clearopbeep(cap->oap); } #ifdef FEAT_FOLDING // Redraw when 'foldenable' changed if (old_fen != curwin->w_p_fen) { # ifdef FEAT_DIFF win_T *wp; if (foldmethodIsDiff(curwin) && curwin->w_p_scb) { // Adjust 'foldenable' in diff-synced windows. FOR_ALL_WINDOWS(wp) { if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb) { wp->w_p_fen = curwin->w_p_fen; changed_window_setting_win(wp); } } } # endif changed_window_setting(); } // Redraw when 'foldlevel' changed. if (old_fdl != curwin->w_p_fdl) newFoldLevel(); #endif } #ifdef FEAT_GUI /* * Vertical scrollbar movement. */ static void nv_ver_scrollbar(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to scroll gui_do_scroll(); } /* * Horizontal scrollbar movement. */ static void nv_hor_scrollbar(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to scroll gui_do_horiz_scroll(scrollbar_value, FALSE); } #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Click in GUI tab. */ static void nv_tabline(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to jump tabs. goto_tabpage(current_tab); } /* * Selected item in tab line menu. */ static void nv_tabmenu(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to jump tabs. handle_tabmenu(); } /* * Handle selecting an item of the GUI tab line menu. * Used in Normal and Insert mode. */ void handle_tabmenu(void) { switch (current_tabmenu) { case TABLINE_MENU_CLOSE: if (current_tab == 0) do_cmdline_cmd((char_u *)"tabclose"); else { vim_snprintf((char *)IObuff, IOSIZE, "tabclose %d", current_tab); do_cmdline_cmd(IObuff); } break; case TABLINE_MENU_NEW: if (current_tab == 0) do_cmdline_cmd((char_u *)"$tabnew"); else { vim_snprintf((char *)IObuff, IOSIZE, "%dtabnew", current_tab - 1); do_cmdline_cmd(IObuff); } break; case TABLINE_MENU_OPEN: if (current_tab == 0) do_cmdline_cmd((char_u *)"browse $tabnew"); else { vim_snprintf((char *)IObuff, IOSIZE, "browse %dtabnew", current_tab - 1); do_cmdline_cmd(IObuff); } break; } } #endif /* * "Q" command. */ static void nv_exmode(cmdarg_T *cap) { /* * Ignore 'Q' in Visual mode, just give a beep. */ if (VIsual_active) vim_beep(BO_EX); else if (!checkclearop(cap->oap)) do_exmode(FALSE); } /* * Handle a ":" command. */ static void nv_colon(cmdarg_T *cap) { int old_p_im; int cmd_result; int is_cmdkey = cap->cmdchar == K_COMMAND; if (VIsual_active && !is_cmdkey) nv_operator(cap); else { if (cap->oap->op_type != OP_NOP) { // Using ":" as a movement is characterwise exclusive. cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; } else if (cap->count0 && !is_cmdkey) { // translate "count:" into ":.,.+(count - 1)" stuffcharReadbuff('.'); if (cap->count0 > 1) { stuffReadbuff((char_u *)",.+"); stuffnumReadbuff((long)cap->count0 - 1L); } } // When typing, don't type below an old message if (KeyTyped) compute_cmdrow(); old_p_im = p_im; // get a command line and execute it cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL, cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0); // If 'insertmode' changed, enter or exit Insert mode if (p_im != old_p_im) { if (p_im) restart_edit = 'i'; else restart_edit = 0; } if (cmd_result == FAIL) // The Ex command failed, do not execute the operator. clearop(cap->oap); else if (cap->oap->op_type != OP_NOP && (cap->oap->start.lnum > curbuf->b_ml.ml_line_count || cap->oap->start.col > (colnr_T)STRLEN(ml_get(cap->oap->start.lnum)) || did_emsg )) // The start of the operator has become invalid by the Ex command. clearopbeep(cap->oap); } } /* * Handle CTRL-G command. */ static void nv_ctrlg(cmdarg_T *cap) { if (VIsual_active) // toggle Selection/Visual mode { VIsual_select = !VIsual_select; showmode(); } else if (!checkclearop(cap->oap)) // print full name if count given or :cd used fileinfo((int)cap->count0, FALSE, TRUE); } /* * Handle CTRL-H <Backspace> command. */ static void nv_ctrlh(cmdarg_T *cap) { if (VIsual_active && VIsual_select) { cap->cmdchar = 'x'; // BS key behaves like 'x' in Select mode v_visop(cap); } else nv_left(cap); } /* * CTRL-L: clear screen and redraw. */ static void nv_clear(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { #ifdef FEAT_SYN_HL // Clear all syntax states to force resyncing. syn_stack_free_all(curwin->w_s); # ifdef FEAT_RELTIME { win_T *wp; FOR_ALL_WINDOWS(wp) wp->w_s->b_syn_slow = FALSE; } # endif #endif redraw_later(CLEAR); #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL)) # ifdef VIMDLL if (!gui.in_use) # endif resize_console_buf(); #endif } } /* * CTRL-O: In Select mode: switch to Visual mode for one command. * Otherwise: Go to older pcmark. */ static void nv_ctrlo(cmdarg_T *cap) { if (VIsual_active && VIsual_select) { VIsual_select = FALSE; showmode(); restart_VIsual_select = 2; // restart Select mode later } else { cap->count1 = -cap->count1; nv_pcmark(cap); } } /* * CTRL-^ command, short for ":e #". Works even when the alternate buffer is * not named. */ static void nv_hat(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) (void)buflist_getfile((int)cap->count0, (linenr_T)0, GETF_SETMARK|GETF_ALT, FALSE); } /* * "Z" commands. */ static void nv_Zet(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { switch (cap->nchar) { // "ZZ": equivalent to ":x". case 'Z': do_cmdline_cmd((char_u *)"x"); break; // "ZQ": equivalent to ":q!" (Elvis compatible). case 'Q': do_cmdline_cmd((char_u *)"q!"); break; default: clearopbeep(cap->oap); } } } /* * Call nv_ident() as if "c1" was used, with "c2" as next character. */ void do_nv_ident(int c1, int c2) { oparg_T oa; cmdarg_T ca; clear_oparg(&oa); CLEAR_FIELD(ca); ca.oap = &oa; ca.cmdchar = c1; ca.nchar = c2; nv_ident(&ca); } /* * Handle the commands that use the word under the cursor. * [g] CTRL-] :ta to current identifier * [g] 'K' run program for current identifier * [g] '*' / to current identifier or string * [g] '#' ? to current identifier or string * g ']' :tselect for current identifier */ static void nv_ident(cmdarg_T *cap) { char_u *ptr = NULL; char_u *buf; unsigned buflen; char_u *newbuf; char_u *p; char_u *kp; // value of 'keywordprg' int kp_help; // 'keywordprg' is ":he" int kp_ex; // 'keywordprg' starts with ":" int n = 0; // init for GCC int cmdchar; int g_cmd; // "g" command int tag_cmd = FALSE; char_u *aux_ptr; int isman; int isman_s; if (cap->cmdchar == 'g') // "g*", "g#", "g]" and "gCTRL-]" { cmdchar = cap->nchar; g_cmd = TRUE; } else { cmdchar = cap->cmdchar; g_cmd = FALSE; } if (cmdchar == POUND) // the pound sign, '#' for English keyboards cmdchar = '#'; /* * The "]", "CTRL-]" and "K" commands accept an argument in Visual mode. */ if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K') { if (VIsual_active && get_visual_text(cap, &ptr, &n) == FAIL) return; if (checkclearopq(cap->oap)) return; } if (ptr == NULL && (n = find_ident_under_cursor(&ptr, (cmdchar == '*' || cmdchar == '#') ? FIND_IDENT|FIND_STRING : FIND_IDENT)) == 0) { clearop(cap->oap); return; } // Allocate buffer to put the command in. Inserting backslashes can // double the length of the word. p_kp / curbuf->b_p_kp could be added // and some numbers. kp = (*curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp); kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0); if (kp_help && *skipwhite(ptr) == NUL) { emsg(_(e_noident)); // found white space only return; } kp_ex = (*kp == ':'); buflen = (unsigned)(n * 2 + 30 + STRLEN(kp)); buf = alloc(buflen); if (buf == NULL) return; buf[0] = NUL; switch (cmdchar) { case '*': case '#': /* * Put cursor at start of word, makes search skip the word * under the cursor. * Call setpcmark() first, so "*``" puts the cursor back where * it was. */ setpcmark(); curwin->w_cursor.col = (colnr_T) (ptr - ml_get_curline()); if (!g_cmd && vim_iswordp(ptr)) STRCPY(buf, "\\<"); no_smartcase = TRUE; // don't use 'smartcase' now break; case 'K': if (kp_help) STRCPY(buf, "he! "); else if (kp_ex) { if (cap->count0 != 0) vim_snprintf((char *)buf, buflen, "%s %ld", kp, cap->count0); else STRCPY(buf, kp); STRCAT(buf, " "); } else { // An external command will probably use an argument starting // with "-" as an option. To avoid trouble we skip the "-". while (*ptr == '-' && n > 0) { ++ptr; --n; } if (n == 0) { emsg(_(e_noident)); // found dashes only vim_free(buf); return; } // When a count is given, turn it into a range. Is this // really what we want? isman = (STRCMP(kp, "man") == 0); isman_s = (STRCMP(kp, "man -s") == 0); if (cap->count0 != 0 && !(isman || isman_s)) sprintf((char *)buf, ".,.+%ld", cap->count0 - 1); STRCAT(buf, "! "); if (cap->count0 == 0 && isman_s) STRCAT(buf, "man"); else STRCAT(buf, kp); STRCAT(buf, " "); if (cap->count0 != 0 && (isman || isman_s)) { sprintf((char *)buf + STRLEN(buf), "%ld", cap->count0); STRCAT(buf, " "); } } break; case ']': tag_cmd = TRUE; #ifdef FEAT_CSCOPE if (p_cst) STRCPY(buf, "cstag "); else #endif STRCPY(buf, "ts "); break; default: tag_cmd = TRUE; if (curbuf->b_help) STRCPY(buf, "he! "); else { if (g_cmd) STRCPY(buf, "tj "); else if (cap->count0 == 0) STRCPY(buf, "ta "); else sprintf((char *)buf, ":%ldta ", cap->count0); } } /* * Now grab the chars in the identifier */ if (cmdchar == 'K' && !kp_help) { ptr = vim_strnsave(ptr, n); if (kp_ex) // Escape the argument properly for an Ex command p = vim_strsave_fnameescape(ptr, FALSE); else // Escape the argument properly for a shell command p = vim_strsave_shellescape(ptr, TRUE, TRUE); vim_free(ptr); if (p == NULL) { vim_free(buf); return; } newbuf = vim_realloc(buf, STRLEN(buf) + STRLEN(p) + 1); if (newbuf == NULL) { vim_free(buf); vim_free(p); return; } buf = newbuf; STRCAT(buf, p); vim_free(p); } else { if (cmdchar == '*') aux_ptr = (char_u *)(magic_isset() ? "/.*~[^$\\" : "/^$\\"); else if (cmdchar == '#') aux_ptr = (char_u *)(magic_isset() ? "/?.*~[^$\\" : "/?^$\\"); else if (tag_cmd) { if (curbuf->b_help) // ":help" handles unescaped argument aux_ptr = (char_u *)""; else aux_ptr = (char_u *)"\\|\"\n["; } else aux_ptr = (char_u *)"\\|\"\n*?["; p = buf + STRLEN(buf); while (n-- > 0) { // put a backslash before \ and some others if (vim_strchr(aux_ptr, *ptr) != NULL) *p++ = '\\'; // When current byte is a part of multibyte character, copy all // bytes of that character. if (has_mbyte) { int i; int len = (*mb_ptr2len)(ptr) - 1; for (i = 0; i < len && n >= 1; ++i, --n) *p++ = *ptr++; } *p++ = *ptr++; } *p = NUL; } /* * Execute the command. */ if (cmdchar == '*' || cmdchar == '#') { if (!g_cmd && (has_mbyte ? vim_iswordp(mb_prevptr(ml_get_curline(), ptr)) : vim_iswordc(ptr[-1]))) STRCAT(buf, "\\>"); // put pattern in search history init_history(); add_to_history(HIST_SEARCH, buf, TRUE, NUL); (void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL); } else { g_tag_at_cursor = TRUE; do_cmdline_cmd(buf); g_tag_at_cursor = FALSE; } vim_free(buf); } /* * Get visually selected text, within one line only. * Returns FAIL if more than one line selected. */ int get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (has_mbyte) // Correct the length to include the whole last character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; } reset_VIsual_and_resel(); return OK; } /* * CTRL-T: backwards in tag stack */ static void nv_tagpop(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) do_tag((char_u *)"", DT_POP, (int)cap->count1, FALSE, TRUE); } /* * Handle scrolling command 'H', 'L' and 'M'. */ static void nv_scroll(cmdarg_T *cap) { int used = 0; long n; #ifdef FEAT_FOLDING linenr_T lnum; #endif int half; cap->oap->motion_type = MLINE; setpcmark(); if (cap->cmdchar == 'L') { validate_botline(); // make sure curwin->w_botline is valid curwin->w_cursor.lnum = curwin->w_botline - 1; if (cap->count1 - 1 >= curwin->w_cursor.lnum) curwin->w_cursor.lnum = 1; else { #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { // Count a fold for one screen line. for (n = cap->count1 - 1; n > 0 && curwin->w_cursor.lnum > curwin->w_topline; --n) { (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); --curwin->w_cursor.lnum; } } else #endif curwin->w_cursor.lnum -= cap->count1 - 1; } } else { if (cap->cmdchar == 'M') { #ifdef FEAT_DIFF // Don't count filler lines above the window. used -= diff_check_fill(curwin, curwin->w_topline) - curwin->w_topfill; #endif validate_botline(); // make sure w_empty_rows is valid half = (curwin->w_height - curwin->w_empty_rows + 1) / 2; for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; ++n) { #ifdef FEAT_DIFF // Count half he number of filler lines to be "below this // line" and half to be "above the next line". if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline + n) / 2 >= half) { --n; break; } #endif used += plines(curwin->w_topline + n); if (used >= half) break; #ifdef FEAT_FOLDING if (hasFolding(curwin->w_topline + n, NULL, &lnum)) n = lnum - curwin->w_topline; #endif } if (n > 0 && used > curwin->w_height) --n; } else // (cap->cmdchar == 'H') { n = cap->count1 - 1; #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { // Count a fold for one screen line. lnum = curwin->w_topline; while (n-- > 0 && lnum < curwin->w_botline - 1) { (void)hasFolding(lnum, NULL, &lnum); ++lnum; } n = lnum - curwin->w_topline; } #endif } curwin->w_cursor.lnum = curwin->w_topline + n; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; } // Correct for 'so', except when an operator is pending. if (cap->oap->op_type == OP_NOP) cursor_correct(); beginline(BL_SOL | BL_FIX); } /* * Cursor right commands. */ static void nv_right(cmdarg_T *cap) { long n; int past_line; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { // <C-Right> and <S-Right> move a word or WORD right if (mod_mask & MOD_MASK_CTRL) cap->arg = TRUE; nv_wordcmd(cap); return; } cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; past_line = (VIsual_active && *p_sel != 'o'); /* * In virtual edit mode, there's no such thing as "past_line", as lines * are (theoretically) infinitely long. */ if (virtual_active()) past_line = 0; for (n = cap->count1; n > 0; --n) { if ((!past_line && oneright() == FAIL) || (past_line && *ml_get_cursor() == NUL) ) { /* * <Space> wraps to next line if 'whichwrap' has 's'. * 'l' wraps to next line if 'whichwrap' has 'l'. * CURS_RIGHT wraps to next line if 'whichwrap' has '>'. */ if ( ((cap->cmdchar == ' ' && vim_strchr(p_ww, 's') != NULL) || (cap->cmdchar == 'l' && vim_strchr(p_ww, 'l') != NULL) || (cap->cmdchar == K_RIGHT && vim_strchr(p_ww, '>') != NULL)) && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { // When deleting we also count the NL as a character. // Set cap->oap->inclusive when last char in the line is // included, move to next line after that if ( cap->oap->op_type != OP_NOP && !cap->oap->inclusive && !LINEEMPTY(curwin->w_cursor.lnum)) cap->oap->inclusive = TRUE; else { ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; curwin->w_set_curswant = TRUE; cap->oap->inclusive = FALSE; } continue; } if (cap->oap->op_type == OP_NOP) { // Only beep and flush if not moved at all if (n == cap->count1) beep_flush(); } else { if (!LINEEMPTY(curwin->w_cursor.lnum)) cap->oap->inclusive = TRUE; } break; } else if (past_line) { curwin->w_set_curswant = TRUE; if (virtual_active()) oneright(); else { if (has_mbyte) curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor()); else ++curwin->w_cursor.col; } } } #ifdef FEAT_FOLDING if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Cursor left commands. * * Returns TRUE when operator end should not be adjusted. */ static void nv_left(cmdarg_T *cap) { long n; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { // <C-Left> and <S-Left> move a word or WORD left if (mod_mask & MOD_MASK_CTRL) cap->arg = 1; nv_bck_word(cap); return; } cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; for (n = cap->count1; n > 0; --n) { if (oneleft() == FAIL) { // <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'. // 'h' wraps to previous line if 'whichwrap' has 'h'. // CURS_LEFT wraps to previous line if 'whichwrap' has '<'. if ( (((cap->cmdchar == K_BS || cap->cmdchar == Ctrl_H) && vim_strchr(p_ww, 'b') != NULL) || (cap->cmdchar == 'h' && vim_strchr(p_ww, 'h') != NULL) || (cap->cmdchar == K_LEFT && vim_strchr(p_ww, '<') != NULL)) && curwin->w_cursor.lnum > 1) { --(curwin->w_cursor.lnum); coladvance((colnr_T)MAXCOL); curwin->w_set_curswant = TRUE; // When the NL before the first char has to be deleted we // put the cursor on the NUL after the previous line. // This is a very special case, be careful! // Don't adjust op_end now, otherwise it won't work. if ( (cap->oap->op_type == OP_DELETE || cap->oap->op_type == OP_CHANGE) && !LINEEMPTY(curwin->w_cursor.lnum)) { char_u *cp = ml_get_cursor(); if (*cp != NUL) { if (has_mbyte) curwin->w_cursor.col += (*mb_ptr2len)(cp); else ++curwin->w_cursor.col; } cap->retval |= CA_NO_ADJ_OP_END; } continue; } // Only beep and flush if not moved at all else if (cap->oap->op_type == OP_NOP && n == cap->count1) beep_flush(); break; } } #ifdef FEAT_FOLDING if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Cursor up commands. * cap->arg is TRUE for "-": Move cursor to first non-blank. */ static void nv_up(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { // <S-Up> is page up cap->arg = BACKWARD; nv_page(cap); } else { cap->oap->motion_type = MLINE; if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if (cap->arg) beginline(BL_WHITE | BL_FIX); } } /* * Cursor down commands. * cap->arg is TRUE for CR and "+": Move cursor to first non-blank. */ static void nv_down(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { // <S-Down> is page down cap->arg = FORWARD; nv_page(cap); } #if defined(FEAT_QUICKFIX) // Quickfix window only: view the result under the cursor. else if (bt_quickfix(curbuf) && cap->cmdchar == CAR) qf_view_result(FALSE); #endif else { #ifdef FEAT_CMDWIN // In the cmdline window a <CR> executes the command. if (cmdwin_type != 0 && cap->cmdchar == CAR) cmdwin_result = CAR; else #endif #ifdef FEAT_JOB_CHANNEL // In a prompt buffer a <CR> in the last line invokes the callback. if (bt_prompt(curbuf) && cap->cmdchar == CAR && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { invoke_prompt_callback(); if (restart_edit == 0) restart_edit = 'a'; } else #endif { cap->oap->motion_type = MLINE; if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if (cap->arg) beginline(BL_WHITE | BL_FIX); } } } #ifdef FEAT_SEARCHPATH /* * Grab the file name under the cursor and edit it. */ static void nv_gotofile(cmdarg_T *cap) { char_u *ptr; linenr_T lnum = -1; if (text_locked()) { clearopbeep(cap->oap); text_locked_msg(); return; } if (curbuf_locked()) { clearop(cap->oap); return; } #ifdef FEAT_PROP_POPUP if (ERROR_IF_TERM_POPUP_WINDOW) return; #endif ptr = grab_file_name(cap->count1, &lnum); if (ptr != NULL) { // do autowrite if necessary if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !buf_hide(curbuf)) (void)autowrite(curbuf, FALSE); setpcmark(); if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST, buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK && cap->nchar == 'F' && lnum >= 0) { curwin->w_cursor.lnum = lnum; check_cursor_lnum(); beginline(BL_SOL | BL_FIX); } vim_free(ptr); } else clearop(cap->oap); } #endif /* * <End> command: to end of current line or last line. */ static void nv_end(cmdarg_T *cap) { if (cap->arg || (mod_mask & MOD_MASK_CTRL)) // CTRL-END = goto last line { cap->arg = TRUE; nv_goto(cap); cap->count1 = 1; // to end of current line } nv_dollar(cap); } /* * Handle the "$" command. */ static void nv_dollar(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = TRUE; // In virtual mode when off the edge of a line and an operator // is pending (whew!) keep the cursor where it is. // Otherwise, send it to the end of the line. if (!virtual_active() || gchar_cursor() != NUL || cap->oap->op_type == OP_NOP) curwin->w_curswant = MAXCOL; // so we stay at the end if (cursor_down((long)(cap->count1 - 1), cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Implementation of '?' and '/' commands. * If cap->arg is TRUE don't set PC mark. */ static void nv_search(cmdarg_T *cap) { oparg_T *oap = cap->oap; pos_T save_cursor = curwin->w_cursor; if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13) { // Translate "g??" to "g?g?" cap->cmdchar = 'g'; cap->nchar = '?'; nv_operator(cap); return; } // When using 'incsearch' the cursor may be moved to set a different search // start position. cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0, TRUE); if (cap->searchbuf == NULL) { clearop(oap); return; } (void)normal_search(cap, cap->cmdchar, cap->searchbuf, (cap->arg || !EQUAL_POS(save_cursor, curwin->w_cursor)) ? 0 : SEARCH_MARK, NULL); } /* * Handle "N" and "n" commands. * cap->arg is SEARCH_REV for "N", 0 for "n". */ static void nv_next(cmdarg_T *cap) { pos_T old = curwin->w_cursor; int wrapped = FALSE; int i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, &wrapped); if (i == 1 && !wrapped && EQUAL_POS(old, curwin->w_cursor)) { // Avoid getting stuck on the current cursor position, which can // happen when an offset is given and the cursor is on the last char // in the buffer: Repeat with count + 1. cap->count1 += 1; (void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, NULL); cap->count1 -= 1; } } /* * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat). * Uses only cap->count1 and cap->oap from "cap". * Return 0 for failure, 1 for found, 2 for found and line offset added. */ static int normal_search( cmdarg_T *cap, int dir, char_u *pat, int opt, // extra flags for do_search() int *wrapped) { int i; searchit_arg_T sia; cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; cap->oap->use_reg_one = TRUE; curwin->w_set_curswant = TRUE; CLEAR_FIELD(sia); i = do_search(cap->oap, dir, dir, pat, cap->count1, opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, &sia); if (wrapped != NULL) *wrapped = sia.sa_wrapped; if (i == 0) clearop(cap->oap); else { if (i == 2) cap->oap->motion_type = MLINE; curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) foldOpenCursor(); #endif } // "/$" will put the cursor after the end of the line, may need to // correct that here check_cursor(); return i; } /* * Character search commands. * cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for * ',' and FALSE for ';'. * cap->nchar is NUL for ',' and ';' (repeat the search) */ static void nv_csearch(cmdarg_T *cap) { int t_cmd; if (cap->cmdchar == 't' || cap->cmdchar == 'T') t_cmd = TRUE; else t_cmd = FALSE; cap->oap->motion_type = MCHAR; if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL) clearopbeep(cap->oap); else { curwin->w_set_curswant = TRUE; // Include a Tab for "tx" and for "dfx". if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD && (t_cmd || cap->oap->op_type != OP_NOP)) { colnr_T scol, ecol; getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol); curwin->w_cursor.coladd = ecol - scol; } else curwin->w_cursor.coladd = 0; adjust_for_sel(cap); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[" and "]" commands. * cap->arg is BACKWARD for "[" and FORWARD for "]". */ static void nv_brackets(cmdarg_T *cap) { pos_T new_pos = {0, 0, 0}; pos_T prev_pos; pos_T *pos = NULL; // init for GCC pos_T old_pos; // cursor position before command int flag; long n; int findc; int c; cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; old_pos = curwin->w_cursor; curwin->w_cursor.coladd = 0; // TODO: don't do this for an error. #ifdef FEAT_SEARCHPATH /* * "[f" or "]f" : Edit file under the cursor (same as "gf") */ if (cap->nchar == 'f') nv_gotofile(cap); else #endif #ifdef FEAT_FIND_ID /* * Find the occurrence(s) of the identifier or define under cursor * in current and included files or jump to the first occurrence. * * search list jump * fwd bwd fwd bwd fwd bwd * identifier "]i" "[i" "]I" "[I" "]^I" "[^I" * define "]d" "[d" "]D" "[D" "]^D" "[^D" */ if (vim_strchr((char_u *) # ifdef EBCDIC "iI\005dD\067", # else "iI\011dD\004", # endif cap->nchar) != NULL) { char_u *ptr; int len; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) clearop(cap->oap); else { find_pattern_in_path(ptr, 0, len, TRUE, cap->count0 == 0 ? !isupper(cap->nchar) : FALSE, ((cap->nchar & 0xf) == ('d' & 0xf)) ? FIND_DEFINE : FIND_ANY, cap->count1, isupper(cap->nchar) ? ACTION_SHOW_ALL : islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO, cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1, (linenr_T)MAXLNUM); curwin->w_set_curswant = TRUE; } } else #endif /* * "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')' * "[#", "]#": go to start/end of Nth innermost #if..#endif construct. * "[/", "[*", "]/", "]*": go to Nth comment start/end. * "[m" or "]m" search for prev/next start of (Java) method. * "[M" or "]M" search for prev/next end of (Java) method. */ if ( (cap->cmdchar == '[' && vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL) || (cap->cmdchar == ']' && vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL)) { if (cap->nchar == '*') cap->nchar = '/'; prev_pos.lnum = 0; if (cap->nchar == 'm' || cap->nchar == 'M') { if (cap->cmdchar == '[') findc = '{'; else findc = '}'; n = 9999; } else { findc = cap->nchar; n = cap->count1; } for ( ; n > 0; --n) { if ((pos = findmatchlimit(cap->oap, findc, (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) { if (new_pos.lnum == 0) // nothing found { if (cap->nchar != 'm' && cap->nchar != 'M') clearopbeep(cap->oap); } else pos = &new_pos; // use last one found break; } prev_pos = new_pos; curwin->w_cursor = *pos; new_pos = *pos; } curwin->w_cursor = old_pos; /* * Handle "[m", "]m", "[M" and "[M". The findmatchlimit() only * brought us to the match for "[m" and "]M" when inside a method. * Try finding the '{' or '}' we want to be at. * Also repeat for the given count. */ if (cap->nchar == 'm' || cap->nchar == 'M') { // norm is TRUE for "]M" and "[m" int norm = ((findc == '{') == (cap->nchar == 'm')); n = cap->count1; // found a match: we were inside a method if (prev_pos.lnum != 0) { pos = &prev_pos; curwin->w_cursor = prev_pos; if (norm) --n; } else pos = NULL; while (n > 0) { for (;;) { if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0) { // if not found anything, that's an error if (pos == NULL) clearopbeep(cap->oap); n = 0; break; } c = gchar_cursor(); if (c == '{' || c == '}') { // Must have found end/start of class: use it. // Or found the place to be at. if ((c == findc && norm) || (n == 1 && !norm)) { new_pos = curwin->w_cursor; pos = &new_pos; n = 0; } // if no match found at all, we started outside of the // class and we're inside now. Just go on. else if (new_pos.lnum == 0) { new_pos = curwin->w_cursor; pos = &new_pos; } // found start/end of other method: go to match else if ((pos = findmatchlimit(cap->oap, findc, (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) n = 0; else curwin->w_cursor = *pos; break; } } --n; } curwin->w_cursor = old_pos; if (pos == NULL && new_pos.lnum != 0) clearopbeep(cap->oap); } if (pos != NULL) { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = TRUE; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[[", "[]", "]]" and "][": move to start or end of function */ else if (cap->nchar == '[' || cap->nchar == ']') { if (cap->nchar == cap->cmdchar) // "]]" or "[[" flag = '{'; else flag = '}'; // "][" or "[]" curwin->w_set_curswant = TRUE; /* * Imitate strange Vi behaviour: When using "]]" with an operator * we also stop at '}'. */ if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag, (cap->oap->op_type != OP_NOP && cap->arg == FORWARD && flag == '{'))) clearopbeep(cap->oap); else { if (cap->oap->op_type == OP_NOP) beginline(BL_WHITE | BL_FIX); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[p", "[P", "]P" and "]p": put with indent adjustment */ else if (cap->nchar == 'p' || cap->nchar == 'P') { nv_put_opt(cap, TRUE); } /* * "['", "[`", "]'" and "]`": jump to next mark */ else if (cap->nchar == '\'' || cap->nchar == '`') { pos = &curwin->w_cursor; for (n = cap->count1; n > 0; --n) { prev_pos = *pos; pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD, cap->nchar == '\''); if (pos == NULL) break; } if (pos == NULL) pos = &prev_pos; nv_cursormark(cap, cap->nchar == '\'', pos); } /* * [ or ] followed by a middle mouse click: put selected text with * indent adjustment. Any other button just does as usual. */ else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE) { (void)do_mouse(cap->oap, cap->nchar, (cap->cmdchar == ']') ? FORWARD : BACKWARD, cap->count1, PUT_FIXINDENT); } #ifdef FEAT_FOLDING /* * "[z" and "]z": move to start or end of open fold. */ else if (cap->nchar == 'z') { if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); } #endif #ifdef FEAT_DIFF /* * "[c" and "]c": move to next or previous diff-change. */ else if (cap->nchar == 'c') { if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); } #endif #ifdef FEAT_SPELL /* * "[s", "[S", "]s" and "]S": move to next spell error. */ else if (cap->nchar == 's' || cap->nchar == 'S') { setpcmark(); for (n = 0; n < cap->count1; ++n) if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0) { clearopbeep(cap->oap); break; } else curwin->w_set_curswant = TRUE; # ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) foldOpenCursor(); # endif } #endif // Not a valid cap->nchar. else clearopbeep(cap->oap); } /* * Handle Normal mode "%" command. */ static void nv_percent(cmdarg_T *cap) { pos_T *pos; #if defined(FEAT_FOLDING) linenr_T lnum = curwin->w_cursor.lnum; #endif cap->oap->inclusive = TRUE; if (cap->count0) // {cnt}% : goto {cnt} percentage in file { if (cap->count0 > 100) clearopbeep(cap->oap); else { cap->oap->motion_type = MLINE; setpcmark(); // Round up, so 'normal 100%' always jumps at the line line. // Beyond 21474836 lines, (ml_line_count * 100 + 99) would // overflow on 32-bits, so use a formula with less accuracy // to avoid overflows. if (curbuf->b_ml.ml_line_count >= 21474836) curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L) / 100L * cap->count0; else curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count * cap->count0 + 99L) / 100L; if (curwin->w_cursor.lnum < 1) curwin->w_cursor.lnum = 1; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; beginline(BL_SOL | BL_FIX); } } else // "%" : go to matching paren { cap->oap->motion_type = MCHAR; cap->oap->use_reg_one = TRUE; if ((pos = findmatch(cap->oap, NUL)) == NULL) clearopbeep(cap->oap); else { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = TRUE; curwin->w_cursor.coladd = 0; adjust_for_sel(cap); } } #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && lnum != curwin->w_cursor.lnum && (fdo_flags & FDO_PERCENT) && KeyTyped) foldOpenCursor(); #endif } /* * Handle "(" and ")" commands. * cap->arg is BACKWARD for "(" and FORWARD for ")". */ static void nv_brace(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->use_reg_one = TRUE; // The motion used to be inclusive for "(", but that is not what Vi does. cap->oap->inclusive = FALSE; curwin->w_set_curswant = TRUE; if (findsent(cap->arg, cap->count1) == FAIL) clearopbeep(cap->oap); else { // Don't leave the cursor on the NUL past end of line. adjust_cursor(cap->oap); curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "m" command: Mark a position. */ static void nv_mark(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { if (setmark(cap->nchar) == FAIL) clearopbeep(cap->oap); } } /* * "{" and "}" commands. * cmd->arg is BACKWARD for "{" and FORWARD for "}". */ static void nv_findpar(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; cap->oap->use_reg_one = TRUE; curwin->w_set_curswant = TRUE; if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE)) clearopbeep(cap->oap); else { curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "u" command: Undo or make lower case. */ static void nv_undo(cmdarg_T *cap) { if (cap->oap->op_type == OP_LOWER || VIsual_active) { // translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" cap->cmdchar = 'g'; cap->nchar = 'u'; nv_operator(cap); } else nv_kundo(cap); } /* * <Undo> command. */ static void nv_kundo(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf)) { clearopbeep(cap->oap); return; } #endif u_undo((int)cap->count1); curwin->w_set_curswant = TRUE; } } /* * Handle the "r" command. */ static void nv_replace(cmdarg_T *cap) { char_u *ptr; int had_ctrl_v; long n; if (checkclearop(cap->oap)) return; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(FALSE); // Don't redo a multibyte character with CTRL-V. if (cap->nchar > DEL) had_ctrl_v = NUL; } else had_ctrl_v = NUL; // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } // Visual mode "r" if (VIsual_active) { if (got_int) reset_VIsual(); if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. if (cap->nchar == CAR) cap->nchar = REPLACE_CR_NCHAR; else if (cap->nchar == NL) cap->nchar = REPLACE_NL_NCHAR; } nv_operator(cap); return; } // Break tabs, etc. if (virtual_active()) { if (u_save_cursor() == FAIL) return; if (gchar_cursor() == NUL) { // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); curwin->w_cursor.col -= cap->count1; } else if (gchar_cursor() == TAB) coladvance_force(getviscol()); } // Abort if not enough characters to replace. ptr = ml_get_cursor(); if (STRLEN(ptr) < (unsigned)cap->count1 || (has_mbyte && mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } /* * Replacing with a TAB is done by edit() when it is complicated because * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB. * Other characters are done below to avoid problems with things like * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC). */ if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) { stuffnumReadbuff(cap->count1); stuffcharReadbuff('R'); stuffcharReadbuff('\t'); stuffcharReadbuff(ESC); return; } // save line for undo if (u_save_cursor() == FAIL) return; if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* * Replace character(s) by a single newline. * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of * autoindent. The insert command depends on being on the last * character of a line or not. */ (void)del_chars(cap->count1, FALSE); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, TRUE, 'r', FALSE); } else { prep_redo(cap->oap->regname, cap->count1, NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; if (has_mbyte) { int old_State = State; if (cap->ncharC1 != 0) AppendCharToRedobuff(cap->ncharC1); if (cap->ncharC2 != 0) AppendCharToRedobuff(cap->ncharC2); // This is slow, but it handles replacing a single-byte with a // multi-byte and the other way around. Also handles adding // composing characters for utf-8. for (n = cap->count1; n > 0; --n) { State = REPLACE; if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ins_char(c); else // will be decremented further down ++curwin->w_cursor.col; } else ins_char(cap->nchar); State = old_State; if (cap->ncharC1 != 0) ins_char(cap->ncharC1); if (cap->ncharC2 != 0) ins_char(cap->ncharC2); } } else { /* * Replace the characters within one line. */ for (n = cap->count1; n > 0; --n) { /* * Get ptr again, because u_save and/or showmatch() will have * released the line. At the same time we let know that the * line will be changed. */ ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ptr[curwin->w_cursor.col] = c; } else ptr[curwin->w_cursor.col] = cap->nchar; if (p_sm && msg_silent == 0) showmatch(cap->nchar); ++curwin->w_cursor.col; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1); netbeans_removed(curbuf, curwin->w_cursor.lnum, start, (long)cap->count1); netbeans_inserted(curbuf, curwin->w_cursor.lnum, start, &ptr[start], (int)cap->count1); } #endif // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, (colnr_T)(curwin->w_cursor.col - cap->count1)); } --curwin->w_cursor.col; // cursor on the last replaced char // if the character on the left of the current cursor is a multi-byte // character, move two characters left if (has_mbyte) mb_adjust_cursor(); curbuf->b_op_end = curwin->w_cursor; curwin->w_set_curswant = TRUE; set_last_insert(cap->nchar); } } /* * 'o': Exchange start and end of Visual area. * 'O': same, but in block mode exchange left and right corners. */ static void v_swap_corners(int cmdchar) { pos_T old_cursor; colnr_T left, right; if (cmdchar == 'O' && VIsual_mode == Ctrl_V) { old_cursor = curwin->w_cursor; getvcols(curwin, &old_cursor, &VIsual, &left, &right); curwin->w_cursor.lnum = VIsual.lnum; coladvance(left); VIsual = curwin->w_cursor; curwin->w_cursor.lnum = old_cursor.lnum; curwin->w_curswant = right; // 'selection "exclusive" and cursor at right-bottom corner: move it // right one column if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e') ++curwin->w_curswant; coladvance(curwin->w_curswant); if (curwin->w_cursor.col == old_cursor.col && (!virtual_active() || curwin->w_cursor.coladd == old_cursor.coladd)) { curwin->w_cursor.lnum = VIsual.lnum; if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e') ++right; coladvance(right); VIsual = curwin->w_cursor; curwin->w_cursor.lnum = old_cursor.lnum; coladvance(left); curwin->w_curswant = left; } } else { old_cursor = curwin->w_cursor; curwin->w_cursor = VIsual; VIsual = old_cursor; curwin->w_set_curswant = TRUE; } } /* * "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE). */ static void nv_Replace(cmdarg_T *cap) { if (VIsual_active) // "R" is replace lines { cap->cmdchar = 'c'; cap->nchar = NUL; VIsual_mode_orig = VIsual_mode; // remember original area for gv VIsual_mode = 'V'; nv_operator(cap); } else if (!checkclearopq(cap->oap)) { if (!curbuf->b_p_ma) emsg(_(e_cannot_make_changes_modifiable_is_off)); else { if (virtual_active()) coladvance(getviscol()); invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE); } } } /* * "gr". */ static void nv_vreplace(cmdarg_T *cap) { if (VIsual_active) { cap->cmdchar = 'r'; cap->nchar = cap->extra_char; nv_replace(cap); // Do same as "r" in Visual mode for now } else if (!checkclearopq(cap->oap)) { if (!curbuf->b_p_ma) emsg(_(e_cannot_make_changes_modifiable_is_off)); else { if (cap->extra_char == Ctrl_V) // get another character cap->extra_char = get_literal(FALSE); stuffcharReadbuff(cap->extra_char); stuffcharReadbuff(ESC); if (virtual_active()) coladvance(getviscol()); invoke_edit(cap, TRUE, 'v', FALSE); } } } /* * Swap case for "~" command, when it does not work like an operator. */ static void n_swapchar(cmdarg_T *cap) { long n; pos_T startpos; int did_change = 0; #ifdef FEAT_NETBEANS_INTG pos_T pos; char_u *ptr; int count; #endif if (checkclearopq(cap->oap)) return; if (LINEEMPTY(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL) { clearopbeep(cap->oap); return; } prep_redo_cmd(cap); if (u_save_cursor() == FAIL) return; startpos = curwin->w_cursor; #ifdef FEAT_NETBEANS_INTG pos = startpos; #endif for (n = cap->count1; n > 0; --n) { did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor); inc_cursor(); if (gchar_cursor() == NUL) { if (vim_strchr(p_ww, '~') != NULL && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { if (did_change) { ptr = ml_get(pos.lnum); count = (int)STRLEN(ptr) - pos.col; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); } pos.col = 0; pos.lnum++; } #endif ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; if (n > 1) { if (u_savesub(curwin->w_cursor.lnum) == FAIL) break; u_clearline(); } } else break; } } #ifdef FEAT_NETBEANS_INTG if (did_change && netbeans_active()) { ptr = ml_get(pos.lnum); count = curwin->w_cursor.col - pos.col; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); } #endif check_cursor(); curwin->w_set_curswant = TRUE; if (did_change) { changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1, 0L); curbuf->b_op_start = startpos; curbuf->b_op_end = curwin->w_cursor; if (curbuf->b_op_end.col > 0) --curbuf->b_op_end.col; } } /* * Move cursor to mark. */ static void nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos) { if (check_mark(pos) == FAIL) clearop(cap->oap); else { if (cap->cmdchar == '\'' || cap->cmdchar == '`' || cap->cmdchar == '[' || cap->cmdchar == ']') setpcmark(); curwin->w_cursor = *pos; if (flag) beginline(BL_WHITE | BL_FIX); else check_cursor(); } cap->oap->motion_type = flag ? MLINE : MCHAR; if (cap->cmdchar == '`') cap->oap->use_reg_one = TRUE; cap->oap->inclusive = FALSE; // ignored if not MCHAR curwin->w_set_curswant = TRUE; } /* * Handle commands that are operators in Visual mode. */ static void v_visop(cmdarg_T *cap) { static char_u trans[] = "YyDdCcxdXdAAIIrr"; // Uppercase means linewise, except in block mode, then "D" deletes till // the end of the line, and "C" replaces till EOL if (isupper(cap->cmdchar)) { if (VIsual_mode != Ctrl_V) { VIsual_mode_orig = VIsual_mode; VIsual_mode = 'V'; } else if (cap->cmdchar == 'C' || cap->cmdchar == 'D') curwin->w_curswant = MAXCOL; } cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1); nv_operator(cap); } /* * "s" and "S" commands. */ static void nv_subst(cmdarg_T *cap) { #ifdef FEAT_TERMINAL // When showing output of term_dumpdiff() swap the top and bottom. if (term_swap_diff() == OK) return; #endif #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif if (VIsual_active) // "vs" and "vS" are the same as "vc" { if (cap->cmdchar == 'S') { VIsual_mode_orig = VIsual_mode; VIsual_mode = 'V'; } cap->cmdchar = 'c'; nv_operator(cap); } else nv_optrans(cap); } /* * Abbreviated commands. */ static void nv_abbrev(cmdarg_T *cap) { if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL) cap->cmdchar = 'x'; // DEL key behaves like 'x' // in Visual mode these commands are operators if (VIsual_active) v_visop(cap); else nv_optrans(cap); } /* * Translate a command into another command. */ static void nv_optrans(cmdarg_T *cap) { static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh", (char_u *)"d$", (char_u *)"c$", (char_u *)"cl", (char_u *)"cc", (char_u *)"yy", (char_u *)":s\r"}; static char_u *str = (char_u *)"xXDCsSY&"; if (!checkclearopq(cap->oap)) { // In Vi "2D" doesn't delete the next line. Can't translate it // either, because "2." should also not use the count. if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL) { cap->oap->start = curwin->w_cursor; cap->oap->op_type = OP_DELETE; #ifdef FEAT_EVAL set_op_var(OP_DELETE); #endif cap->count1 = 1; nv_dollar(cap); finish_op = TRUE; ResetRedobuff(); AppendCharToRedobuff('D'); } else { if (cap->count0) stuffnumReadbuff(cap->count0); stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]); } } cap->opcount = 0; } /* * "'" and "`" commands. Also for "g'" and "g`". * cap->arg is TRUE for "'" and "g'". */ static void nv_gomark(cmdarg_T *cap) { pos_T *pos; int c; #ifdef FEAT_FOLDING pos_T old_cursor = curwin->w_cursor; int old_KeyTyped = KeyTyped; // getting file may reset it #endif if (cap->cmdchar == 'g') c = cap->extra_char; else c = cap->nchar; pos = getmark(c, (cap->oap->op_type == OP_NOP)); if (pos == (pos_T *)-1) // jumped to other file { if (cap->arg) { check_cursor_lnum(); beginline(BL_WHITE | BL_FIX); } else check_cursor(); } else nv_cursormark(cap, cap->arg, pos); // May need to clear the coladd that a mark includes. if (!virtual_active()) curwin->w_cursor.coladd = 0; check_cursor_col(); #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && pos != NULL && (pos == (pos_T *)-1 || !EQUAL_POS(old_cursor, *pos)) && (fdo_flags & FDO_MARK) && old_KeyTyped) foldOpenCursor(); #endif } /* * Handle CTRL-O, CTRL-I, "g;", "g," and "CTRL-Tab" commands. */ static void nv_pcmark(cmdarg_T *cap) { #ifdef FEAT_JUMPLIST pos_T *pos; # ifdef FEAT_FOLDING linenr_T lnum = curwin->w_cursor.lnum; int old_KeyTyped = KeyTyped; // getting file may reset it # endif if (!checkclearopq(cap->oap)) { if (cap->cmdchar == TAB && mod_mask == MOD_MASK_CTRL) { if (goto_tabpage_lastused() == FAIL) clearopbeep(cap->oap); return; } if (cap->cmdchar == 'g') pos = movechangelist((int)cap->count1); else pos = movemark((int)cap->count1); if (pos == (pos_T *)-1) // jump to other file { curwin->w_set_curswant = TRUE; check_cursor(); } else if (pos != NULL) // can jump nv_cursormark(cap, FALSE, pos); else if (cap->cmdchar == 'g') { if (curbuf->b_changelistlen == 0) emsg(_("E664: changelist is empty")); else if (cap->count1 < 0) emsg(_("E662: At start of changelist")); else emsg(_("E663: At end of changelist")); } else clearopbeep(cap->oap); # ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum) && (fdo_flags & FDO_MARK) && old_KeyTyped) foldOpenCursor(); # endif } #else clearopbeep(cap->oap); #endif } /* * Handle '"' command. */ static void nv_regname(cmdarg_T *cap) { if (checkclearop(cap->oap)) return; #ifdef FEAT_EVAL if (cap->nchar == '=') cap->nchar = get_expr_register(); #endif if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE)) { cap->oap->regname = cap->nchar; cap->opcount = cap->count0; // remember count before '"' #ifdef FEAT_EVAL set_reg_var(cap->oap->regname); #endif } else clearopbeep(cap->oap); } /* * Handle "v", "V" and "CTRL-V" commands. * Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg * is TRUE. * Handle CTRL-Q just like CTRL-V. */ static void nv_visual(cmdarg_T *cap) { if (cap->cmdchar == Ctrl_Q) cap->cmdchar = Ctrl_V; // 'v', 'V' and CTRL-V can be used while an operator is pending to make it // characterwise, linewise, or blockwise. if (cap->oap->op_type != OP_NOP) { motion_force = cap->oap->motion_force = cap->cmdchar; finish_op = FALSE; // operator doesn't finish now but later return; } VIsual_select = cap->arg; if (VIsual_active) // change Visual mode { if (VIsual_mode == cap->cmdchar) // stop visual mode end_visual_mode(); else // toggle char/block mode { // or char/line mode VIsual_mode = cap->cmdchar; showmode(); } redraw_curbuf_later(INVERTED); // update the inversion } else // start Visual mode { check_visual_highlight(); if (cap->count0 > 0 && resel_VIsual_mode != NUL) { // use previously selected part VIsual = curwin->w_cursor; VIsual_active = TRUE; VIsual_reselect = TRUE; if (!cap->arg) // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); setmouse(); if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later /* * For V and ^V, we multiply the number of lines even if there * was only one -- webb */ if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1) { curwin->w_cursor.lnum += resel_VIsual_line_count * cap->count0 - 1; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; } VIsual_mode = resel_VIsual_mode; if (VIsual_mode == 'v') { if (resel_VIsual_line_count <= 1) { validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + resel_VIsual_vcol * cap->count0 - 1; } else curwin->w_curswant = resel_VIsual_vcol; coladvance(curwin->w_curswant); } if (resel_VIsual_vcol == MAXCOL) { curwin->w_curswant = MAXCOL; coladvance((colnr_T)MAXCOL); } else if (VIsual_mode == Ctrl_V) { validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + resel_VIsual_vcol * cap->count0 - 1; coladvance(curwin->w_curswant); } else curwin->w_set_curswant = TRUE; redraw_curbuf_later(INVERTED); // show the inversion } else { if (!cap->arg) // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); n_start_visual_mode(cap->cmdchar); if (VIsual_mode != 'V' && *p_sel == 'e') ++cap->count1; // include one more char if (cap->count0 > 0 && --cap->count1 > 0) { // With a count select that many characters or lines. if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V) nv_right(cap); else if (VIsual_mode == 'V') nv_down(cap); } } } } /* * Start selection for Shift-movement keys. */ void start_selection(void) { // if 'selectmode' contains "key", start Select mode may_start_select('k'); n_start_visual_mode('v'); } /* * Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu. */ void may_start_select(int c) { VIsual_select = (stuff_empty() && typebuf_typed() && (vim_strchr(p_slm, c) != NULL)); } /* * Start Visual mode "c". * Should set VIsual_select before calling this. */ static void n_start_visual_mode(int c) { #ifdef FEAT_CONCEAL int cursor_line_was_concealed = curwin->w_p_cole > 0 && conceal_cursor_line(curwin); #endif VIsual_mode = c; VIsual_active = TRUE; VIsual_reselect = TRUE; // Corner case: the 0 position in a tab may change when going into // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting. if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB) { validate_virtcol(); coladvance(curwin->w_virtcol); } VIsual = curwin->w_cursor; #ifdef FEAT_FOLDING foldAdjustVisual(); #endif setmouse(); #ifdef FEAT_CONCEAL // Check if redraw is needed after changing the state. conceal_check_cursor_line(cursor_line_was_concealed); #endif if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end may still be the same, and the selection needs to be owned clip_star.vmode = NUL; #endif // Only need to redraw this line, unless still need to redraw an old // Visual area (when 'lazyredraw' is set). if (curwin->w_redr_type < INVERTED) { curwin->w_old_cursor_lnum = curwin->w_cursor.lnum; curwin->w_old_visual_lnum = curwin->w_cursor.lnum; } } /* * CTRL-W: Window commands */ static void nv_window(cmdarg_T *cap) { if (cap->nchar == ':') { // "CTRL-W :" is the same as typing ":"; useful in a terminal window cap->cmdchar = ':'; cap->nchar = NUL; nv_colon(cap); } else if (!checkclearop(cap->oap)) do_window(cap->nchar, cap->count0, NUL); // everything is in window.c } /* * CTRL-Z: Suspend */ static void nv_suspend(cmdarg_T *cap) { clearop(cap->oap); if (VIsual_active) end_visual_mode(); // stop Visual mode do_cmdline_cmd((char_u *)"stop"); } /* * Commands starting with "g". */ static void nv_g_cmd(cmdarg_T *cap) { oparg_T *oap = cap->oap; pos_T tpos; int i; int flag = FALSE; switch (cap->nchar) { case Ctrl_A: case Ctrl_X: #ifdef MEM_PROFILE /* * "g^A": dump log of used memory. */ if (!VIsual_active && cap->nchar == Ctrl_A) vim_mem_profile_dump(); else #endif /* * "g^A/g^X": sequentially increment visually selected region */ if (VIsual_active) { cap->arg = TRUE; cap->cmdchar = cap->nchar; cap->nchar = NUL; nv_addsub(cap); } else clearopbeep(oap); break; /* * "gR": Enter virtual replace mode. */ case 'R': cap->arg = TRUE; nv_Replace(cap); break; case 'r': nv_vreplace(cap); break; case '&': do_cmdline_cmd((char_u *)"%s//~/&"); break; /* * "gv": Reselect the previous Visual area. If Visual already active, * exchange previous and current Visual area. */ case 'v': if (checkclearop(oap)) break; if ( curbuf->b_visual.vi_start.lnum == 0 || curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count || curbuf->b_visual.vi_end.lnum == 0) beep_flush(); else { // set w_cursor to the start of the Visual area, tpos to the end if (VIsual_active) { i = VIsual_mode; VIsual_mode = curbuf->b_visual.vi_mode; curbuf->b_visual.vi_mode = i; # ifdef FEAT_EVAL curbuf->b_visual_mode_eval = i; # endif i = curwin->w_curswant; curwin->w_curswant = curbuf->b_visual.vi_curswant; curbuf->b_visual.vi_curswant = i; tpos = curbuf->b_visual.vi_end; curbuf->b_visual.vi_end = curwin->w_cursor; curwin->w_cursor = curbuf->b_visual.vi_start; curbuf->b_visual.vi_start = VIsual; } else { VIsual_mode = curbuf->b_visual.vi_mode; curwin->w_curswant = curbuf->b_visual.vi_curswant; tpos = curbuf->b_visual.vi_end; curwin->w_cursor = curbuf->b_visual.vi_start; } VIsual_active = TRUE; VIsual_reselect = TRUE; // Set Visual to the start and w_cursor to the end of the Visual // area. Make sure they are on an existing character. check_cursor(); VIsual = curwin->w_cursor; curwin->w_cursor = tpos; check_cursor(); update_topline(); /* * When called from normal "g" command: start Select mode when * 'selectmode' contains "cmd". When called for K_SELECT, always * start Select mode. */ if (cap->arg) VIsual_select = TRUE; else may_start_select('c'); setmouse(); #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end are still the same, and the selection needs to be owned clip_star.vmode = NUL; #endif redraw_curbuf_later(INVERTED); showmode(); } break; /* * "gV": Don't reselect the previous Visual area after a Select mode * mapping of menu. */ case 'V': VIsual_reselect = FALSE; break; /* * "gh": start Select mode. * "gH": start Select line mode. * "g^H": start Select block mode. */ case K_BS: cap->nchar = Ctrl_H; // FALLTHROUGH case 'h': case 'H': case Ctrl_H: # ifdef EBCDIC // EBCDIC: 'v'-'h' != '^v'-'^h' if (cap->nchar == Ctrl_H) cap->cmdchar = Ctrl_V; else # endif cap->cmdchar = cap->nchar + ('v' - 'h'); cap->arg = TRUE; nv_visual(cap); break; // "gn", "gN" visually select next/previous search match // "gn" selects next match // "gN" selects previous match case 'N': case 'n': if (!current_search(cap->count1, cap->nchar == 'n')) clearopbeep(oap); break; /* * "gj" and "gk" two new funny movement keys -- up and down * movement based on *screen* line rather than *file* line. */ case 'j': case K_DOWN: // with 'nowrap' it works just like the normal "j" command. if (!curwin->w_p_wrap) { oap->motion_type = MLINE; i = cursor_down(cap->count1, oap->op_type == OP_NOP); } else i = nv_screengo(oap, FORWARD, cap->count1); if (i == FAIL) clearopbeep(oap); break; case 'k': case K_UP: // with 'nowrap' it works just like the normal "k" command. if (!curwin->w_p_wrap) { oap->motion_type = MLINE; i = cursor_up(cap->count1, oap->op_type == OP_NOP); } else i = nv_screengo(oap, BACKWARD, cap->count1); if (i == FAIL) clearopbeep(oap); break; /* * "gJ": join two lines without inserting a space. */ case 'J': nv_join(cap); break; /* * "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines. * "gm": middle of "g0" and "g$". */ case '^': flag = TRUE; // FALLTHROUGH case '0': case 'm': case K_HOME: case K_KHOME: oap->motion_type = MCHAR; oap->inclusive = FALSE; if (curwin->w_p_wrap && curwin->w_width != 0) { int width1 = curwin->w_width - curwin_col_off(); int width2 = width1 + curwin_col_off2(); validate_virtcol(); i = 0; if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0) i = (curwin->w_virtcol - width1) / width2 * width2 + width1; } else i = curwin->w_leftcol; // Go to the middle of the screen line. When 'number' or // 'relativenumber' is on and lines are wrapping the middle can be more // to the left. if (cap->nchar == 'm') i += (curwin->w_width - curwin_col_off() + ((curwin->w_p_wrap && i > 0) ? curwin_col_off2() : 0)) / 2; coladvance((colnr_T)i); if (flag) { do i = gchar_cursor(); while (VIM_ISWHITE(i) && oneright() == OK); curwin->w_valid &= ~VALID_WCOL; } curwin->w_set_curswant = TRUE; break; case 'M': { char_u *ptr = ml_get_curline(); oap->motion_type = MCHAR; oap->inclusive = FALSE; if (has_mbyte) i = mb_string2cells(ptr, (int)STRLEN(ptr)); else i = (int)STRLEN(ptr); if (cap->count0 > 0 && cap->count0 <= 100) coladvance((colnr_T)(i * cap->count0 / 100)); else coladvance((colnr_T)(i / 2)); curwin->w_set_curswant = TRUE; } break; case '_': // "g_": to the last non-blank character in the line or <count> lines // downward. cap->oap->motion_type = MCHAR; cap->oap->inclusive = TRUE; curwin->w_curswant = MAXCOL; if (cursor_down((long)(cap->count1 - 1), cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else { char_u *ptr = ml_get_curline(); // In Visual mode we may end up after the line. if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) --curwin->w_cursor.col; // Decrease the cursor column until it's on a non-blank. while (curwin->w_cursor.col > 0 && VIM_ISWHITE(ptr[curwin->w_cursor.col])) --curwin->w_cursor.col; curwin->w_set_curswant = TRUE; adjust_for_sel(cap); } break; case '$': case K_END: case K_KEND: { int col_off = curwin_col_off(); oap->motion_type = MCHAR; oap->inclusive = TRUE; if (curwin->w_p_wrap && curwin->w_width != 0) { curwin->w_curswant = MAXCOL; // so we stay at the end if (cap->count1 == 1) { int width1 = curwin->w_width - col_off; int width2 = width1 + curwin_col_off2(); validate_virtcol(); i = width1 - 1; if (curwin->w_virtcol >= (colnr_T)width1) i += ((curwin->w_virtcol - width1) / width2 + 1) * width2; coladvance((colnr_T)i); // Make sure we stick in this column. validate_virtcol(); curwin->w_curswant = curwin->w_virtcol; curwin->w_set_curswant = FALSE; if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { /* * Check for landing on a character that got split at * the end of the line. We do not want to advance to * the next screen line. */ if (curwin->w_virtcol > (colnr_T)i) --curwin->w_cursor.col; } } else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL) clearopbeep(oap); } else { if (cap->count1 > 1) // if it fails, let the cursor still move to the last char (void)cursor_down(cap->count1 - 1, FALSE); i = curwin->w_leftcol + curwin->w_width - col_off - 1; coladvance((colnr_T)i); // if the character doesn't fit move one back if (curwin->w_cursor.col > 0 && (*mb_ptr2cells)(ml_get_cursor()) > 1) { colnr_T vcol; getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol); if (vcol >= curwin->w_leftcol + curwin->w_width - col_off) --curwin->w_cursor.col; } // Make sure we stick in this column. validate_virtcol(); curwin->w_curswant = curwin->w_virtcol; curwin->w_set_curswant = FALSE; } } break; /* * "g*" and "g#", like "*" and "#" but without using "\<" and "\>" */ case '*': case '#': #if POUND != '#' case POUND: // pound sign (sometimes equal to '#') #endif case Ctrl_RSB: // :tag or :tselect for current identifier case ']': // :tselect for current identifier nv_ident(cap); break; /* * ge and gE: go back to end of word */ case 'e': case 'E': oap->motion_type = MCHAR; curwin->w_set_curswant = TRUE; oap->inclusive = TRUE; if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL) clearopbeep(oap); break; /* * "g CTRL-G": display info about cursor position */ case Ctrl_G: cursor_pos_info(NULL); break; /* * "gi": start Insert at the last position. */ case 'i': if (curbuf->b_last_insert.lnum != 0) { curwin->w_cursor = curbuf->b_last_insert; check_cursor_lnum(); i = (int)STRLEN(ml_get_curline()); if (curwin->w_cursor.col > (colnr_T)i) { if (virtual_active()) curwin->w_cursor.coladd += curwin->w_cursor.col - i; curwin->w_cursor.col = i; } } cap->cmdchar = 'i'; nv_edit(cap); break; /* * "gI": Start insert in column 1. */ case 'I': beginline(0); if (!checkclearopq(oap)) invoke_edit(cap, FALSE, 'g', FALSE); break; #ifdef FEAT_SEARCHPATH /* * "gf": goto file, edit file under cursor * "]f" and "[f": can also be used. */ case 'f': case 'F': nv_gotofile(cap); break; #endif // "g'm" and "g`m": jump to mark without setting pcmark case '\'': cap->arg = TRUE; // FALLTHROUGH case '`': nv_gomark(cap); break; /* * "gs": Goto sleep. */ case 's': do_sleep(cap->count1 * 1000L, FALSE); break; /* * "ga": Display the ascii value of the character under the * cursor. It is displayed in decimal, hex, and octal. -- webb */ case 'a': do_ascii(NULL); break; /* * "g8": Display the bytes used for the UTF-8 character under the * cursor. It is displayed in hex. * "8g8" finds illegal byte sequence. */ case '8': if (cap->count0 == 8) utf_find_illegal(); else show_utf8(); break; // "g<": show scrollback text case '<': show_sb_text(); break; /* * "gg": Goto the first line in file. With a count it goes to * that line number like for "G". -- webb */ case 'g': cap->arg = FALSE; nv_goto(cap); break; /* * Two-character operators: * "gq" Format text * "gw" Format text and keep cursor position * "g~" Toggle the case of the text. * "gu" Change text to lower case. * "gU" Change text to upper case. * "g?" rot13 encoding * "g@" call 'operatorfunc' */ case 'q': case 'w': oap->cursor_start = curwin->w_cursor; // FALLTHROUGH case '~': case 'u': case 'U': case '?': case '@': nv_operator(cap); break; /* * "gd": Find first occurrence of pattern under the cursor in the * current function * "gD": idem, but in the current file. */ case 'd': case 'D': nv_gd(oap, cap->nchar, (int)cap->count0); break; /* * g<*Mouse> : <C-*mouse> */ case K_MIDDLEMOUSE: case K_MIDDLEDRAG: case K_MIDDLERELEASE: case K_LEFTMOUSE: case K_LEFTDRAG: case K_LEFTRELEASE: case K_MOUSEMOVE: case K_RIGHTMOUSE: case K_RIGHTDRAG: case K_RIGHTRELEASE: case K_X1MOUSE: case K_X1DRAG: case K_X1RELEASE: case K_X2MOUSE: case K_X2DRAG: case K_X2RELEASE: mod_mask = MOD_MASK_CTRL; (void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0); break; case K_IGNORE: break; /* * "gP" and "gp": same as "P" and "p" but leave cursor just after new text */ case 'p': case 'P': nv_put(cap); break; #ifdef FEAT_BYTEOFF // "go": goto byte count from start of buffer case 'o': goto_byte(cap->count0); break; #endif // "gQ": improved Ex mode case 'Q': if (text_locked()) { clearopbeep(cap->oap); text_locked_msg(); break; } if (!checkclearopq(oap)) do_exmode(TRUE); break; #ifdef FEAT_JUMPLIST case ',': nv_pcmark(cap); break; case ';': cap->count1 = -cap->count1; nv_pcmark(cap); break; #endif case 't': if (!checkclearop(oap)) goto_tabpage((int)cap->count0); break; case 'T': if (!checkclearop(oap)) goto_tabpage(-(int)cap->count1); break; case TAB: if (!checkclearop(oap) && goto_tabpage_lastused() == FAIL) clearopbeep(oap); break; case '+': case '-': // "g+" and "g-": undo or redo along the timeline if (!checkclearopq(oap)) undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1, FALSE, FALSE, FALSE); break; default: clearopbeep(oap); break; } } /* * Handle "o" and "O" commands. */ static void n_opencmd(cmdarg_T *cap) { #ifdef FEAT_CONCEAL linenr_T oldline = curwin->w_cursor.lnum; #endif if (!checkclearopq(cap->oap)) { #ifdef FEAT_FOLDING if (cap->cmdchar == 'O') // Open above the first line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); else // Open below the last line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum); #endif if (u_save((linenr_T)(curwin->w_cursor.lnum - (cap->cmdchar == 'O' ? 1 : 0)), (linenr_T)(curwin->w_cursor.lnum + (cap->cmdchar == 'o' ? 1 : 0)) ) == OK && open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD, has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM : 0, 0) == OK) { #ifdef FEAT_CONCEAL if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum) redrawWinline(curwin, oldline); #endif #ifdef FEAT_SYN_HL if (curwin->w_p_cul) // force redraw of cursorline curwin->w_valid &= ~VALID_CROW; #endif // When '#' is in 'cpoptions' ignore the count. if (vim_strchr(p_cpo, CPO_HASH) != NULL) cap->count1 = 1; invoke_edit(cap, FALSE, cap->cmdchar, TRUE); } } } /* * "." command: redo last change. */ static void nv_dot(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { /* * If "restart_edit" is TRUE, the last but one command is repeated * instead of the last command (inserting text). This is used for * CTRL-O <.> in insert mode. */ if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL) clearopbeep(cap->oap); } } /* * CTRL-R: undo undo */ static void nv_redo(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { u_redo((int)cap->count1); curwin->w_set_curswant = TRUE; } } /* * Handle "U" command. */ static void nv_Undo(cmdarg_T *cap) { // In Visual mode and typing "gUU" triggers an operator if (cap->oap->op_type == OP_UPPER || VIsual_active) { // translate "gUU" to "gUgU" cap->cmdchar = 'g'; cap->nchar = 'U'; nv_operator(cap); } else if (!checkclearopq(cap->oap)) { u_undoline(); curwin->w_set_curswant = TRUE; } } /* * '~' command: If tilde is not an operator and Visual is off: swap case of a * single character. */ static void nv_tilde(cmdarg_T *cap) { if (!p_to && !VIsual_active && cap->oap->op_type != OP_TILDE) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif n_swapchar(cap); } else nv_operator(cap); } /* * Handle an operator command. * The actual work is done by do_pending_operator(). */ static void nv_operator(cmdarg_T *cap) { int op_type; op_type = get_op_type(cap->cmdchar, cap->nchar); #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && op_is_change(op_type) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif if (op_type == cap->oap->op_type) // double operator works on lines nv_lineop(cap); else if (!checkclearop(cap->oap)) { cap->oap->start = curwin->w_cursor; cap->oap->op_type = op_type; #ifdef FEAT_EVAL set_op_var(op_type); #endif } } #ifdef FEAT_EVAL /* * Set v:operator to the characters for "optype". */ static void set_op_var(int optype) { char_u opchars[3]; if (optype == OP_NOP) set_vim_var_string(VV_OP, NULL, 0); else { opchars[0] = get_op_char(optype); opchars[1] = get_extra_op_char(optype); opchars[2] = NUL; set_vim_var_string(VV_OP, opchars, -1); } } #endif /* * Handle linewise operator "dd", "yy", etc. * * "_" is is a strange motion command that helps make operators more logical. * It is actually implemented, but not documented in the real Vi. This motion * command actually refers to "the current line". Commands like "dd" and "yy" * are really an alternate form of "d_" and "y_". It does accept a count, so * "d3_" works to delete 3 lines. */ static void nv_lineop(cmdarg_T *cap) { cap->oap->motion_type = MLINE; if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if ( (cap->oap->op_type == OP_DELETE // only with linewise motions && cap->oap->motion_force != 'v' && cap->oap->motion_force != Ctrl_V) || cap->oap->op_type == OP_LSHIFT || cap->oap->op_type == OP_RSHIFT) beginline(BL_SOL | BL_FIX); else if (cap->oap->op_type != OP_YANK) // 'Y' does not move cursor beginline(BL_WHITE | BL_FIX); } /* * <Home> command. */ static void nv_home(cmdarg_T *cap) { // CTRL-HOME is like "gg" if (mod_mask & MOD_MASK_CTRL) nv_goto(cap); else { cap->count0 = 1; nv_pipe(cap); } ins_at_eol = FALSE; // Don't move cursor past eol (only necessary in a // one-character line). } /* * "|" command. */ static void nv_pipe(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; beginline(0); if (cap->count0 > 0) { coladvance((colnr_T)(cap->count0 - 1)); curwin->w_curswant = (colnr_T)(cap->count0 - 1); } else curwin->w_curswant = 0; // keep curswant at the column where we wanted to go, not where // we ended; differs if line is too short curwin->w_set_curswant = FALSE; } /* * Handle back-word command "b" and "B". * cap->arg is 1 for "B" */ static void nv_bck_word(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; curwin->w_set_curswant = TRUE; if (bck_word(cap->count1, cap->arg, FALSE) == FAIL) clearopbeep(cap->oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Handle word motion commands "e", "E", "w" and "W". * cap->arg is TRUE for "E" and "W". */ static void nv_wordcmd(cmdarg_T *cap) { int n; int word_end; int flag = FALSE; pos_T startpos = curwin->w_cursor; /* * Set inclusive for the "E" and "e" command. */ if (cap->cmdchar == 'e' || cap->cmdchar == 'E') word_end = TRUE; else word_end = FALSE; cap->oap->inclusive = word_end; /* * "cw" and "cW" are a special case. */ if (!word_end && cap->oap->op_type == OP_CHANGE) { n = gchar_cursor(); if (n != NUL) // not an empty line { if (VIM_ISWHITE(n)) { /* * Reproduce a funny Vi behaviour: "cw" on a blank only * changes one character, not all blanks until the start of * the next word. Only do this when the 'w' flag is included * in 'cpoptions'. */ if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL) { cap->oap->inclusive = TRUE; cap->oap->motion_type = MCHAR; return; } } else { /* * This is a little strange. To match what the real Vi does, * we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided * that we are not on a space or a TAB. This seems impolite * at first, but it's really more what we mean when we say * 'cw'. * Another strangeness: When standing on the end of a word * "ce" will change until the end of the next word, but "cw" * will change only one character! This is done by setting * flag. */ cap->oap->inclusive = TRUE; word_end = TRUE; flag = TRUE; } } } cap->oap->motion_type = MCHAR; curwin->w_set_curswant = TRUE; if (word_end) n = end_word(cap->count1, cap->arg, flag, FALSE); else n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP); // Don't leave the cursor on the NUL past the end of line. Unless we // didn't move it forward. if (LT_POS(startpos, curwin->w_cursor)) adjust_cursor(cap->oap); if (n == FAIL && cap->oap->op_type == OP_NOP) clearopbeep(cap->oap); else { adjust_for_sel(cap); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * Used after a movement command: If the cursor ends up on the NUL after the * end of the line, may move it back to the last character and make the motion * inclusive. */ static void adjust_cursor(oparg_T *oap) { // The cursor cannot remain on the NUL when: // - the column is > 0 // - not in Visual mode or 'selection' is "o" // - 'virtualedit' is not "all" and not "onemore". if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL && (!VIsual_active || *p_sel == 'o') && !virtual_active() && (get_ve_flags() & VE_ONEMORE) == 0) { --curwin->w_cursor.col; // prevent cursor from moving on the trail byte if (has_mbyte) mb_adjust_cursor(); oap->inclusive = TRUE; } } /* * "0" and "^" commands. * cap->arg is the argument for beginline(). */ static void nv_beginline(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; beginline(cap->arg); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif ins_at_eol = FALSE; // Don't move cursor past eol (only necessary in a // one-character line). } /* * In exclusive Visual mode, may include the last character. */ static void adjust_for_sel(cmdarg_T *cap) { if (VIsual_active && cap->oap->inclusive && *p_sel == 'e' && gchar_cursor() != NUL && LT_POS(VIsual, curwin->w_cursor)) { if (has_mbyte) inc_cursor(); else ++curwin->w_cursor.col; cap->oap->inclusive = FALSE; } } /* * Exclude last character at end of Visual area for 'selection' == "exclusive". * Should check VIsual_mode before calling this. * Returns TRUE when backed up to the previous line. */ int unadjust_for_sel(void) { pos_T *pp; if (*p_sel == 'e' && !EQUAL_POS(VIsual, curwin->w_cursor)) { if (LT_POS(VIsual, curwin->w_cursor)) pp = &curwin->w_cursor; else pp = &VIsual; if (pp->coladd > 0) --pp->coladd; else if (pp->col > 0) { --pp->col; mb_adjustpos(curbuf, pp); } else if (pp->lnum > 1) { --pp->lnum; pp->col = (colnr_T)STRLEN(ml_get(pp->lnum)); return TRUE; } } return FALSE; } /* * SELECT key in Normal or Visual mode: end of Select mode mapping. */ static void nv_select(cmdarg_T *cap) { if (VIsual_active) VIsual_select = TRUE; else if (VIsual_reselect) { cap->nchar = 'v'; // fake "gv" command cap->arg = TRUE; nv_g_cmd(cap); } } /* * "G", "gg", CTRL-END, CTRL-HOME. * cap->arg is TRUE for "G". */ static void nv_goto(cmdarg_T *cap) { linenr_T lnum; if (cap->arg) lnum = curbuf->b_ml.ml_line_count; else lnum = 1L; cap->oap->motion_type = MLINE; setpcmark(); // When a count is given, use it instead of the default lnum if (cap->count0 != 0) lnum = cap->count0; if (lnum < 1L) lnum = 1L; else if (lnum > curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; curwin->w_cursor.lnum = lnum; beginline(BL_SOL | BL_FIX); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * CTRL-\ in Normal mode. */ static void nv_normal(cmdarg_T *cap) { if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G) { clearop(cap->oap); if (restart_edit != 0 && mode_displayed) clear_cmdline = TRUE; // unshow mode later restart_edit = 0; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) cmdwin_result = Ctrl_C; #endif if (VIsual_active) { end_visual_mode(); // stop Visual redraw_curbuf_later(INVERTED); } // CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. if (cap->nchar == Ctrl_G && p_im) restart_edit = 'a'; } else clearopbeep(cap->oap); } /* * ESC in Normal mode: beep, but don't flush buffers. * Don't even beep if we are canceling a command. */ static void nv_esc(cmdarg_T *cap) { int no_reason; no_reason = (cap->oap->op_type == OP_NOP && cap->opcount == 0 && cap->count0 == 0 && cap->oap->regname == 0 && !p_im); if (cap->arg) // TRUE for CTRL-C { if (restart_edit == 0 #ifdef FEAT_CMDWIN && cmdwin_type == 0 #endif && !VIsual_active && no_reason) { if (anyBufIsChanged()) msg(_("Type :qa! and press <Enter> to abandon all changes and exit Vim")); else msg(_("Type :qa and press <Enter> to exit Vim")); } // Don't reset "restart_edit" when 'insertmode' is set, it won't be // set again below when halfway a mapping. if (!p_im) restart_edit = 0; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; got_int = FALSE; // don't stop executing autocommands et al. return; } #endif } #ifdef FEAT_CMDWIN else if (cmdwin_type != 0 && ex_normal_busy) { // When :normal runs out of characters while in the command line window // vgetorpeek() will return ESC. Exit the cmdline window to break the // loop. cmdwin_result = K_IGNORE; return; } #endif if (VIsual_active) { end_visual_mode(); // stop Visual check_cursor_col(); // make sure cursor is not beyond EOL curwin->w_set_curswant = TRUE; redraw_curbuf_later(INVERTED); } else if (no_reason) vim_beep(BO_ESC); clearop(cap->oap); // A CTRL-C is often used at the start of a menu. When 'insertmode' is // set return to Insert mode afterwards. if (restart_edit == 0 && goto_im() && ex_normal_busy == 0) restart_edit = 'a'; } /* * Move the cursor for the "A" command. */ void set_cursor_for_append_to_line(void) { curwin->w_set_curswant = TRUE; if (get_ve_flags() == VE_ALL) { int save_State = State; // Pretend Insert mode here to allow the cursor on the // character past the end of the line State = INSERT; coladvance((colnr_T)MAXCOL); State = save_State; } else curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor()); } /* * Handle "A", "a", "I", "i" and <Insert> commands. * Also handle K_PS, start bracketed paste. */ static void nv_edit(cmdarg_T *cap) { // <Insert> is equal to "i" if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS) cap->cmdchar = 'i'; // in Visual mode "A" and "I" are an operator if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I')) { #ifdef FEAT_TERMINAL if (term_in_normal_mode()) { end_visual_mode(); clearop(cap->oap); term_enter_job_mode(); return; } #endif v_visop(cap); } // in Visual mode and after an operator "a" and "i" are for text objects else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i') && (cap->oap->op_type != OP_NOP || VIsual_active)) { #ifdef FEAT_TEXTOBJ nv_object(cap); #else clearopbeep(cap->oap); #endif } #ifdef FEAT_TERMINAL else if (term_in_normal_mode()) { clearop(cap->oap); term_enter_job_mode(); return; } #endif else if (!curbuf->b_p_ma && !p_im) { // Only give this error when 'insertmode' is off. emsg(_(e_cannot_make_changes_modifiable_is_off)); clearop(cap->oap); if (cap->cmdchar == K_PS) // drop the pasted text bracketed_paste(PASTE_INSERT, TRUE, NULL); } else if (cap->cmdchar == K_PS && VIsual_active) { pos_T old_pos = curwin->w_cursor; pos_T old_visual = VIsual; // In Visual mode the selected text is deleted. if (VIsual_mode == 'V' || curwin->w_cursor.lnum != VIsual.lnum) { shift_delete_registers(); cap->oap->regname = '1'; } else cap->oap->regname = '-'; cap->cmdchar = 'd'; cap->nchar = NUL; nv_operator(cap); do_pending_operator(cap, 0, FALSE); cap->cmdchar = K_PS; // When the last char in the line was deleted then append. Detect this // by checking if the cursor moved to before the Visual area. if (*ml_get_cursor() != NUL && LT_POS(curwin->w_cursor, old_pos) && LT_POS(curwin->w_cursor, old_visual)) inc_cursor(); // Insert to replace the deleted text with the pasted text. invoke_edit(cap, FALSE, cap->cmdchar, FALSE); } else if (!checkclearopq(cap->oap)) { switch (cap->cmdchar) { case 'A': // "A"ppend after the line set_cursor_for_append_to_line(); break; case 'I': // "I"nsert before the first non-blank if (vim_strchr(p_cpo, CPO_INSEND) == NULL) beginline(BL_WHITE); else beginline(BL_WHITE|BL_FIX); break; case K_PS: // Bracketed paste works like "a"ppend, unless the cursor is in // the first column, then it inserts. if (curwin->w_cursor.col == 0) break; // FALLTHROUGH case 'a': // "a"ppend is like "i"nsert on the next character. // increment coladd when in virtual space, increment the // column otherwise, also to append after an unprintable char if (virtual_active() && (curwin->w_cursor.coladd > 0 || *ml_get_cursor() == NUL || *ml_get_cursor() == TAB)) curwin->w_cursor.coladd++; else if (*ml_get_cursor() != NUL) inc_cursor(); break; } if (curwin->w_cursor.coladd && cap->cmdchar != 'A') { int save_State = State; // Pretend Insert mode here to allow the cursor on the // character past the end of the line State = INSERT; coladvance(getviscol()); State = save_State; } invoke_edit(cap, FALSE, cap->cmdchar, FALSE); } else if (cap->cmdchar == K_PS) // drop the pasted text bracketed_paste(PASTE_INSERT, TRUE, NULL); } /* * Invoke edit() and take care of "restart_edit" and the return value. */ static void invoke_edit( cmdarg_T *cap, int repl, // "r" or "gr" command int cmd, int startln) { int restart_edit_save = 0; // Complicated: When the user types "a<C-O>a" we don't want to do Insert // mode recursively. But when doing "a<C-O>." or "a<C-O>rx" we do allow // it. if (repl || !stuff_empty()) restart_edit_save = restart_edit; else restart_edit_save = 0; // Always reset "restart_edit", this is not a restarted edit. restart_edit = 0; if (edit(cmd, startln, cap->count1)) cap->retval |= CA_COMMAND_BUSY; if (restart_edit == 0) restart_edit = restart_edit_save; } #ifdef FEAT_TEXTOBJ /* * "a" or "i" while an operator is pending or in Visual mode: object motion. */ static void nv_object( cmdarg_T *cap) { int flag; int include; char_u *mps_save; if (cap->cmdchar == 'i') include = FALSE; // "ix" = inner object: exclude white space else include = TRUE; // "ax" = an object: include white space // Make sure (), [], {} and <> are in 'matchpairs' mps_save = curbuf->b_p_mps; curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>"; switch (cap->nchar) { case 'w': // "aw" = a word flag = current_word(cap->oap, cap->count1, include, FALSE); break; case 'W': // "aW" = a WORD flag = current_word(cap->oap, cap->count1, include, TRUE); break; case 'b': // "ab" = a braces block case '(': case ')': flag = current_block(cap->oap, cap->count1, include, '(', ')'); break; case 'B': // "aB" = a Brackets block case '{': case '}': flag = current_block(cap->oap, cap->count1, include, '{', '}'); break; case '[': // "a[" = a [] block case ']': flag = current_block(cap->oap, cap->count1, include, '[', ']'); break; case '<': // "a<" = a <> block case '>': flag = current_block(cap->oap, cap->count1, include, '<', '>'); break; case 't': // "at" = a tag block (xml and html) // Do not adjust oap->end in do_pending_operator() // otherwise there are different results for 'dit' // (note leading whitespace in last line): // 1) <b> 2) <b> // foobar foobar // </b> </b> cap->retval |= CA_NO_ADJ_OP_END; flag = current_tagblock(cap->oap, cap->count1, include); break; case 'p': // "ap" = a paragraph flag = current_par(cap->oap, cap->count1, include, 'p'); break; case 's': // "as" = a sentence flag = current_sent(cap->oap, cap->count1, include); break; case '"': // "a"" = a double quoted string case '\'': // "a'" = a single quoted string case '`': // "a`" = a backtick quoted string flag = current_quote(cap->oap, cap->count1, include, cap->nchar); break; #if 0 // TODO case 'S': // "aS" = a section case 'f': // "af" = a filename case 'u': // "au" = a URL #endif default: flag = FAIL; break; } curbuf->b_p_mps = mps_save; if (flag == FAIL) clearopbeep(cap->oap); adjust_cursor_col(); curwin->w_set_curswant = TRUE; } #endif /* * "q" command: Start/stop recording. * "q:", "q/", "q?": edit command-line in command-line window. */ static void nv_record(cmdarg_T *cap) { if (cap->oap->op_type == OP_FORMAT) { // "gqq" is the same as "gqgq": format line cap->cmdchar = 'g'; cap->nchar = 'q'; nv_operator(cap); } else if (!checkclearop(cap->oap)) { #ifdef FEAT_CMDWIN if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?') { stuffcharReadbuff(cap->nchar); stuffcharReadbuff(K_CMDWIN); } else #endif // (stop) recording into a named register, unless executing a // register if (reg_executing == 0 && do_record(cap->nchar) == FAIL) clearopbeep(cap->oap); } } /* * Handle the "@r" command. */ static void nv_at(cmdarg_T *cap) { if (checkclearop(cap->oap)) return; #ifdef FEAT_EVAL if (cap->nchar == '=') { if (get_expr_register() == NUL) return; } #endif while (cap->count1-- && !got_int) { if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL) { clearopbeep(cap->oap); break; } line_breakcheck(); } } /* * Handle the CTRL-U and CTRL-D commands. */ static void nv_halfpage(cmdarg_T *cap) { if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1) || (cap->cmdchar == Ctrl_D && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)) clearopbeep(cap->oap); else if (!checkclearop(cap->oap)) halfpage(cap->cmdchar == Ctrl_D, cap->count0); } /* * Handle "J" or "gJ" command. */ static void nv_join(cmdarg_T *cap) { if (VIsual_active) // join the visual lines nv_operator(cap); else if (!checkclearop(cap->oap)) { if (cap->count0 <= 1) cap->count0 = 2; // default for join is two lines! if (curwin->w_cursor.lnum + cap->count0 - 1 > curbuf->b_ml.ml_line_count) { // can't join when on the last line if (cap->count0 <= 2) { clearopbeep(cap->oap); return; } cap->count0 = curbuf->b_ml.ml_line_count - curwin->w_cursor.lnum + 1; } prep_redo(cap->oap->regname, cap->count0, NUL, cap->cmdchar, NUL, NUL, cap->nchar); (void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE, TRUE); } } /* * "P", "gP", "p" and "gp" commands. */ static void nv_put(cmdarg_T *cap) { nv_put_opt(cap, FALSE); } /* * "P", "gP", "p" and "gp" commands. * "fix_indent" is TRUE for "[p", "[P", "]p" and "]P". */ static void nv_put_opt(cmdarg_T *cap, int fix_indent) { int regname = 0; void *reg1 = NULL, *reg2 = NULL; int empty = FALSE; int was_visual = FALSE; int dir; int flags = 0; if (cap->oap->op_type != OP_NOP) { #ifdef FEAT_DIFF // "dp" is ":diffput" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p') { clearop(cap->oap); nv_diffgetput(TRUE, cap->opcount); } else #endif clearopbeep(cap->oap); } #ifdef FEAT_JOB_CHANNEL else if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); } #endif else { if (fix_indent) { dir = (cap->cmdchar == ']' && cap->nchar == 'p') ? FORWARD : BACKWARD; flags |= PUT_FIXINDENT; } else dir = (cap->cmdchar == 'P' || ((cap->cmdchar == 'g' || cap->cmdchar == 'z') && cap->nchar == 'P')) ? BACKWARD : FORWARD; prep_redo_cmd(cap); if (cap->cmdchar == 'g') flags |= PUT_CURSEND; else if (cap->cmdchar == 'z') flags |= PUT_BLOCK_INNER; if (VIsual_active) { // Putting in Visual mode: The put text replaces the selected // text. First delete the selected text, then put the new text. // Need to save and restore the registers that the delete // overwrites if the old contents is being put. was_visual = TRUE; regname = cap->oap->regname; #ifdef FEAT_CLIPBOARD adjust_clip_reg(&regname); #endif if (regname == 0 || regname == '"' || VIM_ISDIGIT(regname) || regname == '-' #ifdef FEAT_CLIPBOARD || (clip_unnamed && (regname == '*' || regname == '+')) #endif ) { // The delete is going to overwrite the register we want to // put, save it first. reg1 = get_register(regname, TRUE); } // Now delete the selected text. Avoid messages here. cap->cmdchar = 'd'; cap->nchar = NUL; cap->oap->regname = NUL; ++msg_silent; nv_operator(cap); do_pending_operator(cap, 0, FALSE); empty = (curbuf->b_ml.ml_flags & ML_EMPTY); --msg_silent; // delete PUT_LINE_BACKWARD; cap->oap->regname = regname; if (reg1 != NULL) { // Delete probably changed the register we want to put, save // it first. Then put back what was there before the delete. reg2 = get_register(regname, FALSE); put_register(regname, reg1); } // When deleted a linewise Visual area, put the register as // lines to avoid it joined with the next line. When deletion was // characterwise, split a line when putting lines. if (VIsual_mode == 'V') flags |= PUT_LINE; else if (VIsual_mode == 'v') flags |= PUT_LINE_SPLIT; if (VIsual_mode == Ctrl_V && dir == FORWARD) flags |= PUT_LINE_FORWARD; dir = BACKWARD; if ((VIsual_mode != 'V' && curwin->w_cursor.col < curbuf->b_op_start.col) || (VIsual_mode == 'V' && curwin->w_cursor.lnum < curbuf->b_op_start.lnum)) // cursor is at the end of the line or end of file, put // forward. dir = FORWARD; // May have been reset in do_put(). VIsual_active = TRUE; } do_put(cap->oap->regname, NULL, dir, cap->count1, flags); // If a register was saved, put it back now. if (reg2 != NULL) put_register(regname, reg2); // What to reselect with "gv"? Selecting the just put text seems to // be the most useful, since the original text was removed. if (was_visual) { curbuf->b_visual.vi_start = curbuf->b_op_start; curbuf->b_visual.vi_end = curbuf->b_op_end; // need to adjust cursor position if (*p_sel == 'e') inc(&curbuf->b_visual.vi_end); } // When all lines were selected and deleted do_put() leaves an empty // line that needs to be deleted now. if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL) { ml_delete_flags(curbuf->b_ml.ml_line_count, ML_DEL_MESSAGE); deleted_lines(curbuf->b_ml.ml_line_count + 1, 1); // If the cursor was in that line, move it to the end of the last // line. if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; coladvance((colnr_T)MAXCOL); } } auto_format(FALSE, TRUE); } } /* * "o" and "O" commands. */ static void nv_open(cmdarg_T *cap) { #ifdef FEAT_DIFF // "do" is ":diffget" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o') { clearop(cap->oap); nv_diffgetput(FALSE, cap->opcount); } else #endif if (VIsual_active) // switch start and end of visual v_swap_corners(cap->cmdchar); #ifdef FEAT_JOB_CHANNEL else if (bt_prompt(curbuf)) clearopbeep(cap->oap); #endif else n_opencmd(cap); } #ifdef FEAT_NETBEANS_INTG static void nv_nbcmd(cmdarg_T *cap) { netbeans_keycommand(cap->nchar); } #endif #ifdef FEAT_DND static void nv_drop(cmdarg_T *cap UNUSED) { do_put('~', NULL, BACKWARD, 1L, PUT_CURSEND); } #endif /* * Trigger CursorHold event. * When waiting for a character for 'updatetime' K_CURSORHOLD is put in the * input buffer. "did_cursorhold" is set to avoid retriggering. */ static void nv_cursorhold(cmdarg_T *cap) { apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf); did_cursorhold = TRUE; cap->retval |= CA_COMMAND_BUSY; // don't call edit() now }
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * normal.c: Contains the main routine for processing characters in command * mode. Communicates closely with the code in ops.c to handle * the operators. */ #include "vim.h" static int VIsual_mode_orig = NUL; // saved Visual mode #ifdef FEAT_EVAL static void set_vcount_ca(cmdarg_T *cap, int *set_prevcount); #endif static int nv_compare(const void *s1, const void *s2); static void unshift_special(cmdarg_T *cap); #ifdef FEAT_CMDL_INFO static void del_from_showcmd(int); #endif /* * nv_*(): functions called to handle Normal and Visual mode commands. * n_*(): functions called to handle Normal mode commands. * v_*(): functions called to handle Visual mode commands. */ static void nv_ignore(cmdarg_T *cap); static void nv_nop(cmdarg_T *cap); static void nv_error(cmdarg_T *cap); static void nv_help(cmdarg_T *cap); static void nv_addsub(cmdarg_T *cap); static void nv_page(cmdarg_T *cap); static void nv_zet(cmdarg_T *cap); #ifdef FEAT_GUI static void nv_ver_scrollbar(cmdarg_T *cap); static void nv_hor_scrollbar(cmdarg_T *cap); #endif #ifdef FEAT_GUI_TABLINE static void nv_tabline(cmdarg_T *cap); static void nv_tabmenu(cmdarg_T *cap); #endif static void nv_exmode(cmdarg_T *cap); static void nv_colon(cmdarg_T *cap); static void nv_ctrlg(cmdarg_T *cap); static void nv_ctrlh(cmdarg_T *cap); static void nv_clear(cmdarg_T *cap); static void nv_ctrlo(cmdarg_T *cap); static void nv_hat(cmdarg_T *cap); static void nv_Zet(cmdarg_T *cap); static void nv_ident(cmdarg_T *cap); static void nv_tagpop(cmdarg_T *cap); static void nv_scroll(cmdarg_T *cap); static void nv_right(cmdarg_T *cap); static void nv_left(cmdarg_T *cap); static void nv_up(cmdarg_T *cap); static void nv_down(cmdarg_T *cap); static void nv_end(cmdarg_T *cap); static void nv_dollar(cmdarg_T *cap); static void nv_search(cmdarg_T *cap); static void nv_next(cmdarg_T *cap); static int normal_search(cmdarg_T *cap, int dir, char_u *pat, int opt, int *wrapped); static void nv_csearch(cmdarg_T *cap); static void nv_brackets(cmdarg_T *cap); static void nv_percent(cmdarg_T *cap); static void nv_brace(cmdarg_T *cap); static void nv_mark(cmdarg_T *cap); static void nv_findpar(cmdarg_T *cap); static void nv_undo(cmdarg_T *cap); static void nv_kundo(cmdarg_T *cap); static void nv_Replace(cmdarg_T *cap); static void nv_replace(cmdarg_T *cap); static void nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos); static void v_visop(cmdarg_T *cap); static void nv_subst(cmdarg_T *cap); static void nv_abbrev(cmdarg_T *cap); static void nv_optrans(cmdarg_T *cap); static void nv_gomark(cmdarg_T *cap); static void nv_pcmark(cmdarg_T *cap); static void nv_regname(cmdarg_T *cap); static void nv_visual(cmdarg_T *cap); static void n_start_visual_mode(int c); static void nv_window(cmdarg_T *cap); static void nv_suspend(cmdarg_T *cap); static void nv_g_cmd(cmdarg_T *cap); static void nv_dot(cmdarg_T *cap); static void nv_redo(cmdarg_T *cap); static void nv_Undo(cmdarg_T *cap); static void nv_tilde(cmdarg_T *cap); static void nv_operator(cmdarg_T *cap); #ifdef FEAT_EVAL static void set_op_var(int optype); #endif static void nv_lineop(cmdarg_T *cap); static void nv_home(cmdarg_T *cap); static void nv_pipe(cmdarg_T *cap); static void nv_bck_word(cmdarg_T *cap); static void nv_wordcmd(cmdarg_T *cap); static void nv_beginline(cmdarg_T *cap); static void adjust_cursor(oparg_T *oap); static void adjust_for_sel(cmdarg_T *cap); static void nv_select(cmdarg_T *cap); static void nv_goto(cmdarg_T *cap); static void nv_normal(cmdarg_T *cap); static void nv_esc(cmdarg_T *oap); static void nv_edit(cmdarg_T *cap); static void invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln); #ifdef FEAT_TEXTOBJ static void nv_object(cmdarg_T *cap); #endif static void nv_record(cmdarg_T *cap); static void nv_at(cmdarg_T *cap); static void nv_halfpage(cmdarg_T *cap); static void nv_join(cmdarg_T *cap); static void nv_put(cmdarg_T *cap); static void nv_put_opt(cmdarg_T *cap, int fix_indent); static void nv_open(cmdarg_T *cap); #ifdef FEAT_NETBEANS_INTG static void nv_nbcmd(cmdarg_T *cap); #endif #ifdef FEAT_DND static void nv_drop(cmdarg_T *cap); #endif static void nv_cursorhold(cmdarg_T *cap); static char *e_noident = N_("E349: No identifier under cursor"); /* * Function to be called for a Normal or Visual mode command. * The argument is a cmdarg_T. */ typedef void (*nv_func_T)(cmdarg_T *cap); // Values for cmd_flags. #define NV_NCH 0x01 // may need to get a second char #define NV_NCH_NOP (0x02|NV_NCH) // get second char when no operator pending #define NV_NCH_ALW (0x04|NV_NCH) // always get a second char #define NV_LANG 0x08 // second char needs language adjustment #define NV_SS 0x10 // may start selection #define NV_SSS 0x20 // may start selection with shift modifier #define NV_STS 0x40 // may stop selection without shift modif. #define NV_RL 0x80 // 'rightleft' modifies command #define NV_KEEPREG 0x100 // don't clear regname #define NV_NCW 0x200 // not allowed in command-line window /* * Generally speaking, every Normal mode command should either clear any * pending operator (with *clearop*()), or set the motion type variable * oap->motion_type. * * When a cursor motion command is made, it is marked as being a character or * line oriented motion. Then, if an operator is in effect, the operation * becomes character or line oriented accordingly. */ /* * This table contains one entry for every Normal or Visual mode command. * The order doesn't matter, init_normal_cmds() will create a sorted index. * It is faster when all keys from zero to '~' are present. */ static const struct nv_cmd { int cmd_char; // (first) command character nv_func_T cmd_func; // function for this command short_u cmd_flags; // NV_ flags short cmd_arg; // value for ca.arg } nv_cmds[] = { {NUL, nv_error, 0, 0}, {Ctrl_A, nv_addsub, 0, 0}, {Ctrl_B, nv_page, NV_STS, BACKWARD}, {Ctrl_C, nv_esc, 0, TRUE}, {Ctrl_D, nv_halfpage, 0, 0}, {Ctrl_E, nv_scroll_line, 0, TRUE}, {Ctrl_F, nv_page, NV_STS, FORWARD}, {Ctrl_G, nv_ctrlg, 0, 0}, {Ctrl_H, nv_ctrlh, 0, 0}, {Ctrl_I, nv_pcmark, 0, 0}, {NL, nv_down, 0, FALSE}, {Ctrl_K, nv_error, 0, 0}, {Ctrl_L, nv_clear, 0, 0}, {CAR, nv_down, 0, TRUE}, {Ctrl_N, nv_down, NV_STS, FALSE}, {Ctrl_O, nv_ctrlo, 0, 0}, {Ctrl_P, nv_up, NV_STS, FALSE}, {Ctrl_Q, nv_visual, 0, FALSE}, {Ctrl_R, nv_redo, 0, 0}, {Ctrl_S, nv_ignore, 0, 0}, {Ctrl_T, nv_tagpop, NV_NCW, 0}, {Ctrl_U, nv_halfpage, 0, 0}, {Ctrl_V, nv_visual, 0, FALSE}, {'V', nv_visual, 0, FALSE}, {'v', nv_visual, 0, FALSE}, {Ctrl_W, nv_window, 0, 0}, {Ctrl_X, nv_addsub, 0, 0}, {Ctrl_Y, nv_scroll_line, 0, FALSE}, {Ctrl_Z, nv_suspend, 0, 0}, {ESC, nv_esc, 0, FALSE}, {Ctrl_BSL, nv_normal, NV_NCH_ALW, 0}, {Ctrl_RSB, nv_ident, NV_NCW, 0}, {Ctrl_HAT, nv_hat, NV_NCW, 0}, {Ctrl__, nv_error, 0, 0}, {' ', nv_right, 0, 0}, {'!', nv_operator, 0, 0}, {'"', nv_regname, NV_NCH_NOP|NV_KEEPREG, 0}, {'#', nv_ident, 0, 0}, {'$', nv_dollar, 0, 0}, {'%', nv_percent, 0, 0}, {'&', nv_optrans, 0, 0}, {'\'', nv_gomark, NV_NCH_ALW, TRUE}, {'(', nv_brace, 0, BACKWARD}, {')', nv_brace, 0, FORWARD}, {'*', nv_ident, 0, 0}, {'+', nv_down, 0, TRUE}, {',', nv_csearch, 0, TRUE}, {'-', nv_up, 0, TRUE}, {'.', nv_dot, NV_KEEPREG, 0}, {'/', nv_search, 0, FALSE}, {'0', nv_beginline, 0, 0}, {'1', nv_ignore, 0, 0}, {'2', nv_ignore, 0, 0}, {'3', nv_ignore, 0, 0}, {'4', nv_ignore, 0, 0}, {'5', nv_ignore, 0, 0}, {'6', nv_ignore, 0, 0}, {'7', nv_ignore, 0, 0}, {'8', nv_ignore, 0, 0}, {'9', nv_ignore, 0, 0}, {':', nv_colon, 0, 0}, {';', nv_csearch, 0, FALSE}, {'<', nv_operator, NV_RL, 0}, {'=', nv_operator, 0, 0}, {'>', nv_operator, NV_RL, 0}, {'?', nv_search, 0, FALSE}, {'@', nv_at, NV_NCH_NOP, FALSE}, {'A', nv_edit, 0, 0}, {'B', nv_bck_word, 0, 1}, {'C', nv_abbrev, NV_KEEPREG, 0}, {'D', nv_abbrev, NV_KEEPREG, 0}, {'E', nv_wordcmd, 0, TRUE}, {'F', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD}, {'G', nv_goto, 0, TRUE}, {'H', nv_scroll, 0, 0}, {'I', nv_edit, 0, 0}, {'J', nv_join, 0, 0}, {'K', nv_ident, 0, 0}, {'L', nv_scroll, 0, 0}, {'M', nv_scroll, 0, 0}, {'N', nv_next, 0, SEARCH_REV}, {'O', nv_open, 0, 0}, {'P', nv_put, 0, 0}, {'Q', nv_exmode, NV_NCW, 0}, {'R', nv_Replace, 0, FALSE}, {'S', nv_subst, NV_KEEPREG, 0}, {'T', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD}, {'U', nv_Undo, 0, 0}, {'W', nv_wordcmd, 0, TRUE}, {'X', nv_abbrev, NV_KEEPREG, 0}, {'Y', nv_abbrev, NV_KEEPREG, 0}, {'Z', nv_Zet, NV_NCH_NOP|NV_NCW, 0}, {'[', nv_brackets, NV_NCH_ALW, BACKWARD}, {'\\', nv_error, 0, 0}, {']', nv_brackets, NV_NCH_ALW, FORWARD}, {'^', nv_beginline, 0, BL_WHITE | BL_FIX}, {'_', nv_lineop, 0, 0}, {'`', nv_gomark, NV_NCH_ALW, FALSE}, {'a', nv_edit, NV_NCH, 0}, {'b', nv_bck_word, 0, 0}, {'c', nv_operator, 0, 0}, {'d', nv_operator, 0, 0}, {'e', nv_wordcmd, 0, FALSE}, {'f', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD}, {'g', nv_g_cmd, NV_NCH_ALW, FALSE}, {'h', nv_left, NV_RL, 0}, {'i', nv_edit, NV_NCH, 0}, {'j', nv_down, 0, FALSE}, {'k', nv_up, 0, FALSE}, {'l', nv_right, NV_RL, 0}, {'m', nv_mark, NV_NCH_NOP, 0}, {'n', nv_next, 0, 0}, {'o', nv_open, 0, 0}, {'p', nv_put, 0, 0}, {'q', nv_record, NV_NCH, 0}, {'r', nv_replace, NV_NCH_NOP|NV_LANG, 0}, {'s', nv_subst, NV_KEEPREG, 0}, {'t', nv_csearch, NV_NCH_ALW|NV_LANG, FORWARD}, {'u', nv_undo, 0, 0}, {'w', nv_wordcmd, 0, FALSE}, {'x', nv_abbrev, NV_KEEPREG, 0}, {'y', nv_operator, 0, 0}, {'z', nv_zet, NV_NCH_ALW, 0}, {'{', nv_findpar, 0, BACKWARD}, {'|', nv_pipe, 0, 0}, {'}', nv_findpar, 0, FORWARD}, {'~', nv_tilde, 0, 0}, // pound sign {POUND, nv_ident, 0, 0}, {K_MOUSEUP, nv_mousescroll, 0, MSCR_UP}, {K_MOUSEDOWN, nv_mousescroll, 0, MSCR_DOWN}, {K_MOUSELEFT, nv_mousescroll, 0, MSCR_LEFT}, {K_MOUSERIGHT, nv_mousescroll, 0, MSCR_RIGHT}, {K_LEFTMOUSE, nv_mouse, 0, 0}, {K_LEFTMOUSE_NM, nv_mouse, 0, 0}, {K_LEFTDRAG, nv_mouse, 0, 0}, {K_LEFTRELEASE, nv_mouse, 0, 0}, {K_LEFTRELEASE_NM, nv_mouse, 0, 0}, {K_MOUSEMOVE, nv_mouse, 0, 0}, {K_MIDDLEMOUSE, nv_mouse, 0, 0}, {K_MIDDLEDRAG, nv_mouse, 0, 0}, {K_MIDDLERELEASE, nv_mouse, 0, 0}, {K_RIGHTMOUSE, nv_mouse, 0, 0}, {K_RIGHTDRAG, nv_mouse, 0, 0}, {K_RIGHTRELEASE, nv_mouse, 0, 0}, {K_X1MOUSE, nv_mouse, 0, 0}, {K_X1DRAG, nv_mouse, 0, 0}, {K_X1RELEASE, nv_mouse, 0, 0}, {K_X2MOUSE, nv_mouse, 0, 0}, {K_X2DRAG, nv_mouse, 0, 0}, {K_X2RELEASE, nv_mouse, 0, 0}, {K_IGNORE, nv_ignore, NV_KEEPREG, 0}, {K_NOP, nv_nop, 0, 0}, {K_INS, nv_edit, 0, 0}, {K_KINS, nv_edit, 0, 0}, {K_BS, nv_ctrlh, 0, 0}, {K_UP, nv_up, NV_SSS|NV_STS, FALSE}, {K_S_UP, nv_page, NV_SS, BACKWARD}, {K_DOWN, nv_down, NV_SSS|NV_STS, FALSE}, {K_S_DOWN, nv_page, NV_SS, FORWARD}, {K_LEFT, nv_left, NV_SSS|NV_STS|NV_RL, 0}, {K_S_LEFT, nv_bck_word, NV_SS|NV_RL, 0}, {K_C_LEFT, nv_bck_word, NV_SSS|NV_RL|NV_STS, 1}, {K_RIGHT, nv_right, NV_SSS|NV_STS|NV_RL, 0}, {K_S_RIGHT, nv_wordcmd, NV_SS|NV_RL, FALSE}, {K_C_RIGHT, nv_wordcmd, NV_SSS|NV_RL|NV_STS, TRUE}, {K_PAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD}, {K_KPAGEUP, nv_page, NV_SSS|NV_STS, BACKWARD}, {K_PAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD}, {K_KPAGEDOWN, nv_page, NV_SSS|NV_STS, FORWARD}, {K_END, nv_end, NV_SSS|NV_STS, FALSE}, {K_KEND, nv_end, NV_SSS|NV_STS, FALSE}, {K_S_END, nv_end, NV_SS, FALSE}, {K_C_END, nv_end, NV_SSS|NV_STS, TRUE}, {K_HOME, nv_home, NV_SSS|NV_STS, 0}, {K_KHOME, nv_home, NV_SSS|NV_STS, 0}, {K_S_HOME, nv_home, NV_SS, 0}, {K_C_HOME, nv_goto, NV_SSS|NV_STS, FALSE}, {K_DEL, nv_abbrev, 0, 0}, {K_KDEL, nv_abbrev, 0, 0}, {K_UNDO, nv_kundo, 0, 0}, {K_HELP, nv_help, NV_NCW, 0}, {K_F1, nv_help, NV_NCW, 0}, {K_XF1, nv_help, NV_NCW, 0}, {K_SELECT, nv_select, 0, 0}, #ifdef FEAT_GUI {K_VER_SCROLLBAR, nv_ver_scrollbar, 0, 0}, {K_HOR_SCROLLBAR, nv_hor_scrollbar, 0, 0}, #endif #ifdef FEAT_GUI_TABLINE {K_TABLINE, nv_tabline, 0, 0}, {K_TABMENU, nv_tabmenu, 0, 0}, #endif #ifdef FEAT_NETBEANS_INTG {K_F21, nv_nbcmd, NV_NCH_ALW, 0}, #endif #ifdef FEAT_DND {K_DROP, nv_drop, NV_STS, 0}, #endif {K_CURSORHOLD, nv_cursorhold, NV_KEEPREG, 0}, {K_PS, nv_edit, 0, 0}, {K_COMMAND, nv_colon, 0, 0}, }; // Number of commands in nv_cmds[]. #define NV_CMDS_SIZE ARRAY_LENGTH(nv_cmds) // Sorted index of commands in nv_cmds[]. static short nv_cmd_idx[NV_CMDS_SIZE]; // The highest index for which // nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char] static int nv_max_linear; /* * Compare functions for qsort() below, that checks the command character * through the index in nv_cmd_idx[]. */ static int nv_compare(const void *s1, const void *s2) { int c1, c2; // The commands are sorted on absolute value. c1 = nv_cmds[*(const short *)s1].cmd_char; c2 = nv_cmds[*(const short *)s2].cmd_char; if (c1 < 0) c1 = -c1; if (c2 < 0) c2 = -c2; return c1 - c2; } /* * Initialize the nv_cmd_idx[] table. */ void init_normal_cmds(void) { int i; // Fill the index table with a one to one relation. for (i = 0; i < (int)NV_CMDS_SIZE; ++i) nv_cmd_idx[i] = i; // Sort the commands by the command character. qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare); // Find the first entry that can't be indexed by the command character. for (i = 0; i < (int)NV_CMDS_SIZE; ++i) if (i != nv_cmds[nv_cmd_idx[i]].cmd_char) break; nv_max_linear = i - 1; } /* * Search for a command in the commands table. * Returns -1 for invalid command. */ static int find_command(int cmdchar) { int i; int idx; int top, bot; int c; // A multi-byte character is never a command. if (cmdchar >= 0x100) return -1; // We use the absolute value of the character. Special keys have a // negative value, but are sorted on their absolute value. if (cmdchar < 0) cmdchar = -cmdchar; // If the character is in the first part: The character is the index into // nv_cmd_idx[]. if (cmdchar <= nv_max_linear) return nv_cmd_idx[cmdchar]; // Perform a binary search. bot = nv_max_linear + 1; top = NV_CMDS_SIZE - 1; idx = -1; while (bot <= top) { i = (top + bot) / 2; c = nv_cmds[nv_cmd_idx[i]].cmd_char; if (c < 0) c = -c; if (cmdchar == c) { idx = nv_cmd_idx[i]; break; } if (cmdchar > c) bot = i + 1; else top = i - 1; } return idx; } /* * Execute a command in Normal mode. */ void normal_cmd( oparg_T *oap, int toplevel UNUSED) // TRUE when called from main() { cmdarg_T ca; // command arguments int c; int ctrl_w = FALSE; // got CTRL-W command int old_col = curwin->w_curswant; #ifdef FEAT_CMDL_INFO int need_flushbuf; // need to call out_flush() #endif pos_T old_pos; // cursor position before command int mapped_len; static int old_mapped_len = 0; int idx; #ifdef FEAT_EVAL int set_prevcount = FALSE; #endif int save_did_cursorhold = did_cursorhold; CLEAR_FIELD(ca); // also resets ca.retval ca.oap = oap; // Use a count remembered from before entering an operator. After typing // "3d" we return from normal_cmd() and come back here, the "3" is // remembered in "opcount". ca.opcount = opcount; /* * If there is an operator pending, then the command we take this time * will terminate it. Finish_op tells us to finish the operation before * returning this time (unless the operation was cancelled). */ #ifdef CURSOR_SHAPE c = finish_op; #endif finish_op = (oap->op_type != OP_NOP); #ifdef CURSOR_SHAPE if (finish_op != c) { ui_cursor_shape(); // may show different cursor shape # ifdef FEAT_MOUSESHAPE update_mouseshape(-1); # endif } #endif // When not finishing an operator and no register name typed, reset the // count. if (!finish_op && !oap->regname) { ca.opcount = 0; #ifdef FEAT_EVAL set_prevcount = TRUE; #endif } // Restore counts from before receiving K_CURSORHOLD. This means after // typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not // "3 * 2". if (oap->prev_opcount > 0 || oap->prev_count0 > 0) { ca.opcount = oap->prev_opcount; ca.count0 = oap->prev_count0; oap->prev_opcount = 0; oap->prev_count0 = 0; } mapped_len = typebuf_maplen(); State = NORMAL_BUSY; #ifdef USE_ON_FLY_SCROLL dont_scroll = FALSE; // allow scrolling here #endif #ifdef FEAT_EVAL // Set v:count here, when called from main() and not a stuffed // command, so that v:count can be used in an expression mapping // when there is no count. Do set it for redo. if (toplevel && readbuf1_empty()) set_vcount_ca(&ca, &set_prevcount); #endif /* * Get the command character from the user. */ c = safe_vgetc(); LANGMAP_ADJUST(c, get_real_state() != SELECTMODE); /* * If a mapping was started in Visual or Select mode, remember the length * of the mapping. This is used below to not return to Insert mode for as * long as the mapping is being executed. */ if (restart_edit == 0) old_mapped_len = 0; else if (old_mapped_len || (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0)) old_mapped_len = typebuf_maplen(); if (c == NUL) c = K_ZERO; /* * In Select mode, typed text replaces the selection. */ if (VIsual_active && VIsual_select && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER)) { // Fake a "c"hange command. When "restart_edit" is set (e.g., because // 'insertmode' is set) fake a "d"elete command, Insert mode will // restart automatically. // Insert the typed character in the typeahead buffer, so that it can // be mapped in Insert mode. Required for ":lmap" to work. ins_char_typebuf(vgetc_char, vgetc_mod_mask); if (restart_edit != 0) c = 'd'; else c = 'c'; msg_nowait = TRUE; // don't delay going to insert mode old_mapped_len = 0; // do go to Insert mode } #ifdef FEAT_CMDL_INFO need_flushbuf = add_to_showcmd(c); #endif getcount: if (!(VIsual_active && VIsual_select)) { /* * Handle a count before a command and compute ca.count0. * Note that '0' is a command and not the start of a count, but it's * part of a count after other digits. */ while ( (c >= '1' && c <= '9') || (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0'))) { if (c == K_DEL || c == K_KDEL) { ca.count0 /= 10; #ifdef FEAT_CMDL_INFO del_from_showcmd(4); // delete the digit and ~@% #endif } else ca.count0 = ca.count0 * 10 + (c - '0'); if (ca.count0 < 0) // overflow ca.count0 = 999999999L; #ifdef FEAT_EVAL // Set v:count here, when called from main() and not a stuffed // command, so that v:count can be used in an expression mapping // right after the count. Do set it for redo. if (toplevel && readbuf1_empty()) set_vcount_ca(&ca, &set_prevcount); #endif if (ctrl_w) { ++no_mapping; ++allow_keys; // no mapping for nchar, but keys } ++no_zero_mapping; // don't map zero here c = plain_vgetc(); LANGMAP_ADJUST(c, TRUE); --no_zero_mapping; if (ctrl_w) { --no_mapping; --allow_keys; } #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(c); #endif } /* * If we got CTRL-W there may be a/another count */ if (c == Ctrl_W && !ctrl_w && oap->op_type == OP_NOP) { ctrl_w = TRUE; ca.opcount = ca.count0; // remember first count ca.count0 = 0; ++no_mapping; ++allow_keys; // no mapping for nchar, but keys c = plain_vgetc(); // get next character LANGMAP_ADJUST(c, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(c); #endif goto getcount; // jump back } } if (c == K_CURSORHOLD) { // Save the count values so that ca.opcount and ca.count0 are exactly // the same when coming back here after handling K_CURSORHOLD. oap->prev_opcount = ca.opcount; oap->prev_count0 = ca.count0; } else if (ca.opcount != 0) { /* * If we're in the middle of an operator (including after entering a * yank buffer with '"') AND we had a count before the operator, then * that count overrides the current value of ca.count0. * What this means effectively, is that commands like "3dw" get turned * into "d3w" which makes things fall into place pretty neatly. * If you give a count before AND after the operator, they are * multiplied. */ if (ca.count0) ca.count0 *= ca.opcount; else ca.count0 = ca.opcount; if (ca.count0 < 0) // overflow ca.count0 = 999999999L; } /* * Always remember the count. It will be set to zero (on the next call, * above) when there is no pending operator. * When called from main(), save the count for use by the "count" built-in * variable. */ ca.opcount = ca.count0; ca.count1 = (ca.count0 == 0 ? 1 : ca.count0); #ifdef FEAT_EVAL /* * Only set v:count when called from main() and not a stuffed command. * Do set it for redo. */ if (toplevel && readbuf1_empty()) set_vcount(ca.count0, ca.count1, set_prevcount); #endif /* * Find the command character in the table of commands. * For CTRL-W we already got nchar when looking for a count. */ if (ctrl_w) { ca.nchar = c; ca.cmdchar = Ctrl_W; } else ca.cmdchar = c; idx = find_command(ca.cmdchar); if (idx < 0) { // Not a known command: beep. clearopbeep(oap); goto normal_end; } if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW)) { // This command is not allowed while editing a cmdline: beep. clearopbeep(oap); text_locked_msg(); goto normal_end; } if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked()) goto normal_end; /* * In Visual/Select mode, a few keys are handled in a special way. */ if (VIsual_active) { // when 'keymodel' contains "stopsel" may stop Select/Visual mode if (km_stopsel && (nv_cmds[idx].cmd_flags & NV_STS) && !(mod_mask & MOD_MASK_SHIFT)) { end_visual_mode(); redraw_curbuf_later(INVERTED); } // Keys that work different when 'keymodel' contains "startsel" if (km_startsel) { if (nv_cmds[idx].cmd_flags & NV_SS) { unshift_special(&ca); idx = find_command(ca.cmdchar); if (idx < 0) { // Just in case clearopbeep(oap); goto normal_end; } } else if ((nv_cmds[idx].cmd_flags & NV_SSS) && (mod_mask & MOD_MASK_SHIFT)) mod_mask &= ~MOD_MASK_SHIFT; } } #ifdef FEAT_RIGHTLEFT if (curwin->w_p_rl && KeyTyped && !KeyStuffed && (nv_cmds[idx].cmd_flags & NV_RL)) { // Invert horizontal movements and operations. Only when typed by the // user directly, not when the result of a mapping or "x" translated // to "dl". switch (ca.cmdchar) { case 'l': ca.cmdchar = 'h'; break; case K_RIGHT: ca.cmdchar = K_LEFT; break; case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break; case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break; case 'h': ca.cmdchar = 'l'; break; case K_LEFT: ca.cmdchar = K_RIGHT; break; case K_S_LEFT: ca.cmdchar = K_S_RIGHT; break; case K_C_LEFT: ca.cmdchar = K_C_RIGHT; break; case '>': ca.cmdchar = '<'; break; case '<': ca.cmdchar = '>'; break; } idx = find_command(ca.cmdchar); } #endif /* * Get an additional character if we need one. */ if ((nv_cmds[idx].cmd_flags & NV_NCH) && (((nv_cmds[idx].cmd_flags & NV_NCH_NOP) == NV_NCH_NOP && oap->op_type == OP_NOP) || (nv_cmds[idx].cmd_flags & NV_NCH_ALW) == NV_NCH_ALW || (ca.cmdchar == 'q' && oap->op_type == OP_NOP && reg_recording == 0 && reg_executing == 0) || ((ca.cmdchar == 'a' || ca.cmdchar == 'i') && (oap->op_type != OP_NOP || VIsual_active)))) { int *cp; int repl = FALSE; // get character for replace mode int lit = FALSE; // get extra character literally int langmap_active = FALSE; // using :lmap mappings int lang; // getting a text character #ifdef HAVE_INPUT_METHOD int save_smd; // saved value of p_smd #endif ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes // Don't generate a CursorHold event here, most commands can't handle // it, e.g., nv_replace(), nv_csearch(). did_cursorhold = TRUE; if (ca.cmdchar == 'g') { /* * For 'g' get the next character now, so that we can check for * "gr", "g'" and "g`". */ ca.nchar = plain_vgetc(); LANGMAP_ADJUST(ca.nchar, TRUE); #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(ca.nchar); #endif if (ca.nchar == 'r' || ca.nchar == '\'' || ca.nchar == '`' || ca.nchar == Ctrl_BSL) { cp = &ca.extra_char; // need to get a third character if (ca.nchar != 'r') lit = TRUE; // get it literally else repl = TRUE; // get it in replace mode } else cp = NULL; // no third character needed } else { if (ca.cmdchar == 'r') // get it in replace mode repl = TRUE; cp = &ca.nchar; } lang = (repl || (nv_cmds[idx].cmd_flags & NV_LANG)); /* * Get a second or third character. */ if (cp != NULL) { if (repl) { State = REPLACE; // pretend Replace mode #ifdef CURSOR_SHAPE ui_cursor_shape(); // show different cursor shape #endif } if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP) { // Allow mappings defined with ":lmap". --no_mapping; --allow_keys; if (repl) State = LREPLACE; else State = LANGMAP; langmap_active = TRUE; } #ifdef HAVE_INPUT_METHOD save_smd = p_smd; p_smd = FALSE; // Don't let the IM code show the mode here if (lang && curbuf->b_p_iminsert == B_IMODE_IM) im_set_active(TRUE); #endif if ((State & INSERT) && !p_ek) { #ifdef FEAT_JOB_CHANNEL ch_log_output = TRUE; #endif // Disable bracketed paste and modifyOtherKeys here, we won't // recognize the escape sequences with 'esckeys' off. out_str(T_BD); out_str(T_CTE); } *cp = plain_vgetc(); if ((State & INSERT) && !p_ek) { #ifdef FEAT_JOB_CHANNEL ch_log_output = TRUE; #endif // Re-enable bracketed paste mode and modifyOtherKeys out_str(T_BE); out_str(T_CTI); } if (langmap_active) { // Undo the decrement done above ++no_mapping; ++allow_keys; State = NORMAL_BUSY; } #ifdef HAVE_INPUT_METHOD if (lang) { if (curbuf->b_p_iminsert != B_IMODE_LMAP) im_save_status(&curbuf->b_p_iminsert); im_set_active(FALSE); } p_smd = save_smd; #endif State = NORMAL_BUSY; #ifdef FEAT_CMDL_INFO need_flushbuf |= add_to_showcmd(*cp); #endif if (!lit) { #ifdef FEAT_DIGRAPHS // Typing CTRL-K gets a digraph. if (*cp == Ctrl_K && ((nv_cmds[idx].cmd_flags & NV_LANG) || cp == &ca.extra_char) && vim_strchr(p_cpo, CPO_DIGRAPH) == NULL) { c = get_digraph(FALSE); if (c > 0) { *cp = c; # ifdef FEAT_CMDL_INFO // Guessing how to update showcmd here... del_from_showcmd(3); need_flushbuf |= add_to_showcmd(*cp); # endif } } #endif // adjust chars > 127, except after "tTfFr" commands LANGMAP_ADJUST(*cp, !lang); #ifdef FEAT_RIGHTLEFT // adjust Hebrew mapped char if (p_hkmap && lang && KeyTyped) *cp = hkmap(*cp); #endif } /* * When the next character is CTRL-\ a following CTRL-N means the * command is aborted and we go to Normal mode. */ if (cp == &ca.extra_char && ca.nchar == Ctrl_BSL && (ca.extra_char == Ctrl_N || ca.extra_char == Ctrl_G)) { ca.cmdchar = Ctrl_BSL; ca.nchar = ca.extra_char; idx = find_command(ca.cmdchar); } else if ((ca.nchar == 'n' || ca.nchar == 'N') && ca.cmdchar == 'g') ca.oap->op_type = get_op_type(*cp, NUL); else if (*cp == Ctrl_BSL) { long towait = (p_ttm >= 0 ? p_ttm : p_tm); // There is a busy wait here when typing "f<C-\>" and then // something different from CTRL-N. Can't be avoided. while ((c = vpeekc()) <= 0 && towait > 0L) { do_sleep(towait > 50L ? 50L : towait, FALSE); towait -= 50L; } if (c > 0) { c = plain_vgetc(); if (c != Ctrl_N && c != Ctrl_G) vungetc(c); else { ca.cmdchar = Ctrl_BSL; ca.nchar = c; idx = find_command(ca.cmdchar); } } } // When getting a text character and the next character is a // multi-byte character, it could be a composing character. // However, don't wait for it to arrive. Also, do enable mapping, // because if it's put back with vungetc() it's too late to apply // mapping. --no_mapping; while (enc_utf8 && lang && (c = vpeekc()) > 0 && (c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1)) { c = plain_vgetc(); if (!utf_iscomposing(c)) { vungetc(c); // it wasn't, put it back break; } else if (ca.ncharC1 == 0) ca.ncharC1 = c; else ca.ncharC2 = c; } ++no_mapping; } --no_mapping; --allow_keys; } #ifdef FEAT_CMDL_INFO /* * Flush the showcmd characters onto the screen so we can see them while * the command is being executed. Only do this when the shown command was * actually displayed, otherwise this will slow down a lot when executing * mappings. */ if (need_flushbuf) out_flush(); #endif if (ca.cmdchar != K_IGNORE) { if (ex_normal_busy) did_cursorhold = save_did_cursorhold; else did_cursorhold = FALSE; } State = NORMAL; if (ca.nchar == ESC) { clearop(oap); if (restart_edit == 0 && goto_im()) restart_edit = 'a'; goto normal_end; } if (ca.cmdchar != K_IGNORE) { msg_didout = FALSE; // don't scroll screen up for normal command msg_col = 0; } old_pos = curwin->w_cursor; // remember where cursor was // When 'keymodel' contains "startsel" some keys start Select/Visual // mode. if (!VIsual_active && km_startsel) { if (nv_cmds[idx].cmd_flags & NV_SS) { start_selection(); unshift_special(&ca); idx = find_command(ca.cmdchar); } else if ((nv_cmds[idx].cmd_flags & NV_SSS) && (mod_mask & MOD_MASK_SHIFT)) { start_selection(); mod_mask &= ~MOD_MASK_SHIFT; } } /* * Execute the command! * Call the command function found in the commands table. */ ca.arg = nv_cmds[idx].cmd_arg; (nv_cmds[idx].cmd_func)(&ca); /* * If we didn't start or finish an operator, reset oap->regname, unless we * need it later. */ if (!finish_op && !oap->op_type && (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG))) { clearop(oap); #ifdef FEAT_EVAL reset_reg_var(); #endif } // Get the length of mapped chars again after typing a count, second // character or "z333<cr>". if (old_mapped_len > 0) old_mapped_len = typebuf_maplen(); /* * If an operation is pending, handle it. But not for K_IGNORE or * K_MOUSEMOVE. */ if (ca.cmdchar != K_IGNORE && ca.cmdchar != K_MOUSEMOVE) do_pending_operator(&ca, old_col, FALSE); /* * Wait for a moment when a message is displayed that will be overwritten * by the mode message. * In Visual mode and with "^O" in Insert mode, a short message will be * overwritten by the mode message. Wait a bit, until a key is hit. * In Visual mode, it's more important to keep the Visual area updated * than keeping a message (e.g. from a /pat search). * Only do this if the command was typed, not from a mapping. * Don't wait when emsg_silent is non-zero. * Also wait a bit after an error message, e.g. for "^O:". * Don't redraw the screen, it would remove the message. */ if ( ((p_smd && msg_silent == 0 && (restart_edit != 0 || (VIsual_active && old_pos.lnum == curwin->w_cursor.lnum && old_pos.col == curwin->w_cursor.col) ) && (clear_cmdline || redraw_cmdline) && (msg_didout || (msg_didany && msg_scroll)) && !msg_nowait && KeyTyped) || (restart_edit != 0 && !VIsual_active && (msg_scroll || emsg_on_display))) && oap->regname == 0 && !(ca.retval & CA_COMMAND_BUSY) && stuff_empty() && typebuf_typed() && emsg_silent == 0 && !in_assert_fails && !did_wait_return && oap->op_type == OP_NOP) { int save_State = State; // Draw the cursor with the right shape here if (restart_edit != 0) State = INSERT; // If need to redraw, and there is a "keep_msg", redraw before the // delay if (must_redraw && keep_msg != NULL && !emsg_on_display) { char_u *kmsg; kmsg = keep_msg; keep_msg = NULL; // Showmode() will clear keep_msg, but we want to use it anyway. // First update w_topline. setcursor(); update_screen(0); // now reset it, otherwise it's put in the history again keep_msg = kmsg; kmsg = vim_strsave(keep_msg); if (kmsg != NULL) { msg_attr((char *)kmsg, keep_msg_attr); vim_free(kmsg); } } setcursor(); #ifdef CURSOR_SHAPE ui_cursor_shape(); // may show different cursor shape #endif cursor_on(); out_flush(); if (msg_scroll || emsg_on_display) ui_delay(1003L, TRUE); // wait at least one second ui_delay(3003L, FALSE); // wait up to three seconds State = save_State; msg_scroll = FALSE; emsg_on_display = FALSE; } /* * Finish up after executing a Normal mode command. */ normal_end: msg_nowait = FALSE; #ifdef FEAT_EVAL if (finish_op) reset_reg_var(); #endif // Reset finish_op, in case it was set #ifdef CURSOR_SHAPE c = finish_op; #endif finish_op = FALSE; #ifdef CURSOR_SHAPE // Redraw the cursor with another shape, if we were in Operator-pending // mode or did a replace command. if (c || ca.cmdchar == 'r') { ui_cursor_shape(); // may show different cursor shape # ifdef FEAT_MOUSESHAPE update_mouseshape(-1); # endif } #endif #ifdef FEAT_CMDL_INFO if (oap->op_type == OP_NOP && oap->regname == 0 && ca.cmdchar != K_CURSORHOLD) clear_showcmd(); #endif checkpcmark(); // check if we moved since setting pcmark vim_free(ca.searchbuf); if (has_mbyte) mb_adjust_cursor(); if (curwin->w_p_scb && toplevel) { validate_cursor(); // may need to update w_leftcol do_check_scrollbind(TRUE); } if (curwin->w_p_crb && toplevel) { validate_cursor(); // may need to update w_leftcol do_check_cursorbind(); } #ifdef FEAT_TERMINAL // don't go to Insert mode if a terminal has a running job if (term_job_running(curbuf->b_term)) restart_edit = 0; #endif /* * May restart edit(), if we got here with CTRL-O in Insert mode (but not * if still inside a mapping that started in Visual mode). * May switch from Visual to Select mode after CTRL-O command. */ if ( oap->op_type == OP_NOP && ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0) || restart_VIsual_select == 1) && !(ca.retval & CA_COMMAND_BUSY) && stuff_empty() && oap->regname == 0) { if (restart_VIsual_select == 1) { VIsual_select = TRUE; showmode(); restart_VIsual_select = 0; } if (restart_edit != 0 && !VIsual_active && old_mapped_len == 0) (void)edit(restart_edit, FALSE, 1L); } if (restart_VIsual_select == 2) restart_VIsual_select = 1; // Save count before an operator for next time. opcount = ca.opcount; } #ifdef FEAT_EVAL /* * Set v:count and v:count1 according to "cap". * Set v:prevcount only when "set_prevcount" is TRUE. */ static void set_vcount_ca(cmdarg_T *cap, int *set_prevcount) { long count = cap->count0; // multiply with cap->opcount the same way as above if (cap->opcount != 0) count = cap->opcount * (count == 0 ? 1 : count); set_vcount(count, count == 0 ? 1 : count, *set_prevcount); *set_prevcount = FALSE; // only set v:prevcount once } #endif /* * Check if highlighting for Visual mode is possible, give a warning message * if not. */ void check_visual_highlight(void) { static int did_check = FALSE; if (full_screen) { if (!did_check && HL_ATTR(HLF_V) == 0) msg(_("Warning: terminal cannot highlight")); did_check = TRUE; } } #if defined(FEAT_CLIPBOARD) && defined(FEAT_EVAL) /* * Call yank_do_autocmd() for "regname". */ static void call_yank_do_autocmd(int regname) { oparg_T oa; yankreg_T *reg; clear_oparg(&oa); oa.regname = regname; oa.op_type = OP_YANK; oa.is_VIsual = TRUE; reg = get_register(regname, TRUE); yank_do_autocmd(&oa, reg); free_register(reg); } #endif /* * End Visual mode. * This function or the next should ALWAYS be called to end Visual mode, except * from do_pending_operator(). */ void end_visual_mode() { end_visual_mode_keep_button(); reset_held_button(); } void end_visual_mode_keep_button() { #ifdef FEAT_CLIPBOARD /* * If we are using the clipboard, then remember what was selected in case * we need to paste it somewhere while we still own the selection. * Only do this when the clipboard is already owned. Don't want to grab * the selection when hitting ESC. */ if (clip_star.available && clip_star.owned) clip_auto_select(); # if defined(FEAT_EVAL) // Emit a TextYankPost for the automatic copy of the selection into the // star and/or plus register. if (has_textyankpost()) { if (clip_isautosel_star()) call_yank_do_autocmd('*'); if (clip_isautosel_plus()) call_yank_do_autocmd('+'); } # endif #endif VIsual_active = FALSE; setmouse(); mouse_dragging = 0; // Save the current VIsual area for '< and '> marks, and "gv" curbuf->b_visual.vi_mode = VIsual_mode; curbuf->b_visual.vi_start = VIsual; curbuf->b_visual.vi_end = curwin->w_cursor; curbuf->b_visual.vi_curswant = curwin->w_curswant; #ifdef FEAT_EVAL curbuf->b_visual_mode_eval = VIsual_mode; #endif if (!virtual_active()) curwin->w_cursor.coladd = 0; may_clear_cmdline(); adjust_cursor_eol(); } /* * Reset VIsual_active and VIsual_reselect. */ void reset_VIsual_and_resel(void) { if (VIsual_active) { end_visual_mode(); redraw_curbuf_later(INVERTED); // delete the inversion later } VIsual_reselect = FALSE; } /* * Reset VIsual_active and VIsual_reselect if it's set. */ void reset_VIsual(void) { if (VIsual_active) { end_visual_mode(); redraw_curbuf_later(INVERTED); // delete the inversion later VIsual_reselect = FALSE; } } void restore_visual_mode(void) { if (VIsual_mode_orig != NUL) { curbuf->b_visual.vi_mode = VIsual_mode_orig; VIsual_mode_orig = NUL; } } /* * Check for a balloon-eval special item to include when searching for an * identifier. When "dir" is BACKWARD "ptr[-1]" must be valid! * Returns TRUE if the character at "*ptr" should be included. * "dir" is FORWARD or BACKWARD, the direction of searching. * "*colp" is in/decremented if "ptr[-dir]" should also be included. * "bnp" points to a counter for square brackets. */ static int find_is_eval_item( char_u *ptr, int *colp, int *bnp, int dir) { // Accept everything inside []. if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD)) ++*bnp; if (*bnp > 0) { if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD)) --*bnp; return TRUE; } // skip over "s.var" if (*ptr == '.') return TRUE; // two-character item: s->var if (ptr[dir == BACKWARD ? 0 : 1] == '>' && ptr[dir == BACKWARD ? -1 : 0] == '-') { *colp += dir; return TRUE; } return FALSE; } /* * Find the identifier under or to the right of the cursor. * "find_type" can have one of three values: * FIND_IDENT: find an identifier (keyword) * FIND_STRING: find any non-white text * FIND_IDENT + FIND_STRING: find any non-white text, identifier preferred. * FIND_EVAL: find text useful for C program debugging * * There are three steps: * 1. Search forward for the start of an identifier/text. Doesn't move if * already on one. * 2. Search backward for the start of this identifier/text. * This doesn't match the real Vi but I like it a little better and it * shouldn't bother anyone. * 3. Search forward to the end of this identifier/text. * When FIND_IDENT isn't defined, we backup until a blank. * * Returns the length of the text, or zero if no text is found. * If text is found, a pointer to the text is put in "*text". This * points into the current buffer line and is not always NUL terminated. */ int find_ident_under_cursor(char_u **text, int find_type) { return find_ident_at_pos(curwin, curwin->w_cursor.lnum, curwin->w_cursor.col, text, NULL, find_type); } /* * Like find_ident_under_cursor(), but for any window and any position. * However: Uses 'iskeyword' from the current window!. */ int find_ident_at_pos( win_T *wp, linenr_T lnum, colnr_T startcol, char_u **text, int *textcol, // column where "text" starts, can be NULL int find_type) { char_u *ptr; int col = 0; // init to shut up GCC int i; int this_class = 0; int prev_class; int prevcol; int bn = 0; // bracket nesting /* * if i == 0: try to find an identifier * if i == 1: try to find any non-white text */ ptr = ml_get_buf(wp->w_buffer, lnum, FALSE); for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; ++i) { /* * 1. skip to start of identifier/text */ col = startcol; if (has_mbyte) { while (ptr[col] != NUL) { // Stop at a ']' to evaluate "a[x]". if ((find_type & FIND_EVAL) && ptr[col] == ']') break; this_class = mb_get_class(ptr + col); if (this_class != 0 && (i == 1 || this_class != 1)) break; col += (*mb_ptr2len)(ptr + col); } } else while (ptr[col] != NUL && (i == 0 ? !vim_iswordc(ptr[col]) : VIM_ISWHITE(ptr[col])) && (!(find_type & FIND_EVAL) || ptr[col] != ']') ) ++col; // When starting on a ']' count it, so that we include the '['. bn = ptr[col] == ']'; /* * 2. Back up to start of identifier/text. */ if (has_mbyte) { // Remember class of character under cursor. if ((find_type & FIND_EVAL) && ptr[col] == ']') this_class = mb_get_class((char_u *)"a"); else this_class = mb_get_class(ptr + col); while (col > 0 && this_class != 0) { prevcol = col - 1 - (*mb_head_off)(ptr, ptr + col - 1); prev_class = mb_get_class(ptr + prevcol); if (this_class != prev_class && (i == 0 || prev_class == 0 || (find_type & FIND_IDENT)) && (!(find_type & FIND_EVAL) || prevcol == 0 || !find_is_eval_item(ptr + prevcol, &prevcol, &bn, BACKWARD)) ) break; col = prevcol; } // If we don't want just any old text, or we've found an // identifier, stop searching. if (this_class > 2) this_class = 2; if (!(find_type & FIND_STRING) || this_class == 2) break; } else { while (col > 0 && ((i == 0 ? vim_iswordc(ptr[col - 1]) : (!VIM_ISWHITE(ptr[col - 1]) && (!(find_type & FIND_IDENT) || !vim_iswordc(ptr[col - 1])))) || ((find_type & FIND_EVAL) && col > 1 && find_is_eval_item(ptr + col - 1, &col, &bn, BACKWARD)) )) --col; // If we don't want just any old text, or we've found an // identifier, stop searching. if (!(find_type & FIND_STRING) || vim_iswordc(ptr[col])) break; } } if (ptr[col] == NUL || (i == 0 && (has_mbyte ? this_class != 2 : !vim_iswordc(ptr[col])))) { // didn't find an identifier or text if ((find_type & FIND_NOERROR) == 0) { if (find_type & FIND_STRING) emsg(_("E348: No string under cursor")); else emsg(_(e_noident)); } return 0; } ptr += col; *text = ptr; if (textcol != NULL) *textcol = col; /* * 3. Find the end if the identifier/text. */ bn = 0; startcol -= col; col = 0; if (has_mbyte) { // Search for point of changing multibyte character class. this_class = mb_get_class(ptr); while (ptr[col] != NUL && ((i == 0 ? mb_get_class(ptr + col) == this_class : mb_get_class(ptr + col) != 0) || ((find_type & FIND_EVAL) && col <= (int)startcol && find_is_eval_item(ptr + col, &col, &bn, FORWARD)) )) col += (*mb_ptr2len)(ptr + col); } else while ((i == 0 ? vim_iswordc(ptr[col]) : (ptr[col] != NUL && !VIM_ISWHITE(ptr[col]))) || ((find_type & FIND_EVAL) && col <= (int)startcol && find_is_eval_item(ptr + col, &col, &bn, FORWARD)) ) ++col; return col; } /* * Prepare for redo of a normal command. */ static void prep_redo_cmd(cmdarg_T *cap) { prep_redo(cap->oap->regname, cap->count0, NUL, cap->cmdchar, NUL, NUL, cap->nchar); } /* * Prepare for redo of any command. * Note that only the last argument can be a multi-byte char. */ void prep_redo( int regname, long num, int cmd1, int cmd2, int cmd3, int cmd4, int cmd5) { ResetRedobuff(); if (regname != 0) // yank from specified buffer { AppendCharToRedobuff('"'); AppendCharToRedobuff(regname); } if (num) AppendNumberToRedobuff(num); if (cmd1 != NUL) AppendCharToRedobuff(cmd1); if (cmd2 != NUL) AppendCharToRedobuff(cmd2); if (cmd3 != NUL) AppendCharToRedobuff(cmd3); if (cmd4 != NUL) AppendCharToRedobuff(cmd4); if (cmd5 != NUL) AppendCharToRedobuff(cmd5); } /* * check for operator active and clear it * * return TRUE if operator was active */ static int checkclearop(oparg_T *oap) { if (oap->op_type == OP_NOP) return FALSE; clearopbeep(oap); return TRUE; } /* * Check for operator or Visual active. Clear active operator. * * Return TRUE if operator or Visual was active. */ static int checkclearopq(oparg_T *oap) { if (oap->op_type == OP_NOP && !VIsual_active) return FALSE; clearopbeep(oap); return TRUE; } void clearop(oparg_T *oap) { oap->op_type = OP_NOP; oap->regname = 0; oap->motion_force = NUL; oap->use_reg_one = FALSE; motion_force = NUL; } void clearopbeep(oparg_T *oap) { clearop(oap); beep_flush(); } /* * Remove the shift modifier from a special key. */ static void unshift_special(cmdarg_T *cap) { switch (cap->cmdchar) { case K_S_RIGHT: cap->cmdchar = K_RIGHT; break; case K_S_LEFT: cap->cmdchar = K_LEFT; break; case K_S_UP: cap->cmdchar = K_UP; break; case K_S_DOWN: cap->cmdchar = K_DOWN; break; case K_S_HOME: cap->cmdchar = K_HOME; break; case K_S_END: cap->cmdchar = K_END; break; } cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask); } /* * If the mode is currently displayed clear the command line or update the * command displayed. */ void may_clear_cmdline(void) { if (mode_displayed) clear_cmdline = TRUE; // unshow visual mode later #ifdef FEAT_CMDL_INFO else clear_showcmd(); #endif } #if defined(FEAT_CMDL_INFO) || defined(PROTO) /* * Routines for displaying a partly typed command */ #define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30 static char_u showcmd_buf[SHOWCMD_BUFLEN]; static char_u old_showcmd_buf[SHOWCMD_BUFLEN]; // For push_showcmd() static int showcmd_is_clear = TRUE; static int showcmd_visual = FALSE; static void display_showcmd(void); void clear_showcmd(void) { if (!p_sc) return; if (VIsual_active && !char_avail()) { int cursor_bot = LT_POS(VIsual, curwin->w_cursor); long lines; colnr_T leftcol, rightcol; linenr_T top, bot; // Show the size of the Visual area. if (cursor_bot) { top = VIsual.lnum; bot = curwin->w_cursor.lnum; } else { top = curwin->w_cursor.lnum; bot = VIsual.lnum; } # ifdef FEAT_FOLDING // Include closed folds as a whole. (void)hasFolding(top, &top, NULL); (void)hasFolding(bot, NULL, &bot); # endif lines = bot - top + 1; if (VIsual_mode == Ctrl_V) { # ifdef FEAT_LINEBREAK char_u *saved_sbr = p_sbr; char_u *saved_w_sbr = curwin->w_p_sbr; // Make 'sbr' empty for a moment to get the correct size. p_sbr = empty_option; curwin->w_p_sbr = empty_option; # endif getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol); # ifdef FEAT_LINEBREAK p_sbr = saved_sbr; curwin->w_p_sbr = saved_w_sbr; # endif sprintf((char *)showcmd_buf, "%ldx%ld", lines, (long)(rightcol - leftcol + 1)); } else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum) sprintf((char *)showcmd_buf, "%ld", lines); else { char_u *s, *e; int l; int bytes = 0; int chars = 0; if (cursor_bot) { s = ml_get_pos(&VIsual); e = ml_get_cursor(); } else { s = ml_get_cursor(); e = ml_get_pos(&VIsual); } while ((*p_sel != 'e') ? s <= e : s < e) { l = (*mb_ptr2len)(s); if (l == 0) { ++bytes; ++chars; break; // end of line } bytes += l; ++chars; s += l; } if (bytes == chars) sprintf((char *)showcmd_buf, "%d", chars); else sprintf((char *)showcmd_buf, "%d-%d", chars, bytes); } showcmd_buf[SHOWCMD_COLS] = NUL; // truncate showcmd_visual = TRUE; } else { showcmd_buf[0] = NUL; showcmd_visual = FALSE; // Don't actually display something if there is nothing to clear. if (showcmd_is_clear) return; } display_showcmd(); } /* * Add 'c' to string of shown command chars. * Return TRUE if output has been written (and setcursor() has been called). */ int add_to_showcmd(int c) { char_u *p; int old_len; int extra_len; int overflow; int i; static int ignore[] = { #ifdef FEAT_GUI K_VER_SCROLLBAR, K_HOR_SCROLLBAR, K_LEFTMOUSE_NM, K_LEFTRELEASE_NM, #endif K_IGNORE, K_PS, K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE, K_MOUSEMOVE, K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE, K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE, K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT, K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE, K_CURSORHOLD, 0 }; if (!p_sc || msg_silent != 0) return FALSE; if (showcmd_visual) { showcmd_buf[0] = NUL; showcmd_visual = FALSE; } // Ignore keys that are scrollbar updates and mouse clicks if (IS_SPECIAL(c)) for (i = 0; ignore[i] != 0; ++i) if (ignore[i] == c) return FALSE; p = transchar(c); if (*p == ' ') STRCPY(p, "<20>"); old_len = (int)STRLEN(showcmd_buf); extra_len = (int)STRLEN(p); overflow = old_len + extra_len - SHOWCMD_COLS; if (overflow > 0) mch_memmove(showcmd_buf, showcmd_buf + overflow, old_len - overflow + 1); STRCAT(showcmd_buf, p); if (char_avail()) return FALSE; display_showcmd(); return TRUE; } void add_to_showcmd_c(int c) { if (!add_to_showcmd(c)) setcursor(); } /* * Delete 'len' characters from the end of the shown command. */ static void del_from_showcmd(int len) { int old_len; if (!p_sc) return; old_len = (int)STRLEN(showcmd_buf); if (len > old_len) len = old_len; showcmd_buf[old_len - len] = NUL; if (!char_avail()) display_showcmd(); } /* * push_showcmd() and pop_showcmd() are used when waiting for the user to type * something and there is a partial mapping. */ void push_showcmd(void) { if (p_sc) STRCPY(old_showcmd_buf, showcmd_buf); } void pop_showcmd(void) { if (!p_sc) return; STRCPY(showcmd_buf, old_showcmd_buf); display_showcmd(); } static void display_showcmd(void) { int len; cursor_off(); len = (int)STRLEN(showcmd_buf); if (len == 0) showcmd_is_clear = TRUE; else { screen_puts(showcmd_buf, (int)Rows - 1, sc_col, 0); showcmd_is_clear = FALSE; } /* * clear the rest of an old message by outputting up to SHOWCMD_COLS * spaces */ screen_puts((char_u *)" " + len, (int)Rows - 1, sc_col + len, 0); setcursor(); // put cursor back where it belongs } #endif /* * When "check" is FALSE, prepare for commands that scroll the window. * When "check" is TRUE, take care of scroll-binding after the window has * scrolled. Called from normal_cmd() and edit(). */ void do_check_scrollbind(int check) { static win_T *old_curwin = NULL; static linenr_T old_topline = 0; #ifdef FEAT_DIFF static int old_topfill = 0; #endif static buf_T *old_buf = NULL; static colnr_T old_leftcol = 0; if (check && curwin->w_p_scb) { // If a ":syncbind" command was just used, don't scroll, only reset // the values. if (did_syncbind) did_syncbind = FALSE; else if (curwin == old_curwin) { /* * Synchronize other windows, as necessary according to * 'scrollbind'. Don't do this after an ":edit" command, except * when 'diff' is set. */ if ((curwin->w_buffer == old_buf #ifdef FEAT_DIFF || curwin->w_p_diff #endif ) && (curwin->w_topline != old_topline #ifdef FEAT_DIFF || curwin->w_topfill != old_topfill #endif || curwin->w_leftcol != old_leftcol)) { check_scrollbind(curwin->w_topline - old_topline, (long)(curwin->w_leftcol - old_leftcol)); } } else if (vim_strchr(p_sbo, 'j')) // jump flag set in 'scrollopt' { /* * When switching between windows, make sure that the relative * vertical offset is valid for the new window. The relative * offset is invalid whenever another 'scrollbind' window has * scrolled to a point that would force the current window to * scroll past the beginning or end of its buffer. When the * resync is performed, some of the other 'scrollbind' windows may * need to jump so that the current window's relative position is * visible on-screen. */ check_scrollbind(curwin->w_topline - curwin->w_scbind_pos, 0L); } curwin->w_scbind_pos = curwin->w_topline; } old_curwin = curwin; old_topline = curwin->w_topline; #ifdef FEAT_DIFF old_topfill = curwin->w_topfill; #endif old_buf = curwin->w_buffer; old_leftcol = curwin->w_leftcol; } /* * Synchronize any windows that have "scrollbind" set, based on the * number of rows by which the current window has changed * (1998-11-02 16:21:01 R. Edward Ralston <eralston@computer.org>) */ void check_scrollbind(linenr_T topline_diff, long leftcol_diff) { int want_ver; int want_hor; win_T *old_curwin = curwin; buf_T *old_curbuf = curbuf; int old_VIsual_select = VIsual_select; int old_VIsual_active = VIsual_active; colnr_T tgt_leftcol = curwin->w_leftcol; long topline; long y; /* * check 'scrollopt' string for vertical and horizontal scroll options */ want_ver = (vim_strchr(p_sbo, 'v') && topline_diff != 0); #ifdef FEAT_DIFF want_ver |= old_curwin->w_p_diff; #endif want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || topline_diff != 0)); /* * loop through the scrollbound windows and scroll accordingly */ VIsual_select = VIsual_active = 0; FOR_ALL_WINDOWS(curwin) { curbuf = curwin->w_buffer; // skip original window and windows with 'noscrollbind' if (curwin != old_curwin && curwin->w_p_scb) { /* * do the vertical scroll */ if (want_ver) { #ifdef FEAT_DIFF if (old_curwin->w_p_diff && curwin->w_p_diff) { diff_set_topline(old_curwin, curwin); } else #endif { curwin->w_scbind_pos += topline_diff; topline = curwin->w_scbind_pos; if (topline > curbuf->b_ml.ml_line_count) topline = curbuf->b_ml.ml_line_count; if (topline < 1) topline = 1; y = topline - curwin->w_topline; if (y > 0) scrollup(y, FALSE); else scrolldown(-y, FALSE); } redraw_later(VALID); cursor_correct(); curwin->w_redr_status = TRUE; } /* * do the horizontal scroll */ if (want_hor && curwin->w_leftcol != tgt_leftcol) { curwin->w_leftcol = tgt_leftcol; leftcol_changed(); } } } /* * reset current-window */ VIsual_select = old_VIsual_select; VIsual_active = old_VIsual_active; curwin = old_curwin; curbuf = old_curbuf; } /* * Command character that's ignored. * Used for CTRL-Q and CTRL-S to avoid problems with terminals that use * xon/xoff. */ static void nv_ignore(cmdarg_T *cap) { cap->retval |= CA_COMMAND_BUSY; // don't call edit() now } /* * Command character that doesn't do anything, but unlike nv_ignore() does * start edit(). Used for "startinsert" executed while starting up. */ static void nv_nop(cmdarg_T *cap UNUSED) { } /* * Command character doesn't exist. */ static void nv_error(cmdarg_T *cap) { clearopbeep(cap->oap); } /* * <Help> and <F1> commands. */ static void nv_help(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) ex_help(NULL); } /* * CTRL-A and CTRL-X: Add or subtract from letter or number under cursor. */ static void nv_addsub(cmdarg_T *cap) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) clearopbeep(cap->oap); else #endif if (!VIsual_active && cap->oap->op_type == OP_NOP) { prep_redo_cmd(cap); cap->oap->op_type = cap->cmdchar == Ctrl_A ? OP_NR_ADD : OP_NR_SUB; op_addsub(cap->oap, cap->count1, cap->arg); cap->oap->op_type = OP_NOP; } else if (VIsual_active) nv_operator(cap); else clearop(cap->oap); } /* * CTRL-F, CTRL-B, etc: Scroll page up or down. */ static void nv_page(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { if (mod_mask & MOD_MASK_CTRL) { // <C-PageUp>: tab page back; <C-PageDown>: tab page forward if (cap->arg == BACKWARD) goto_tabpage(-(int)cap->count1); else goto_tabpage((int)cap->count0); } else (void)onepage(cap->arg, cap->count1); } } /* * Implementation of "gd" and "gD" command. */ static void nv_gd( oparg_T *oap, int nchar, int thisblock) // 1 for "1gd" and "1gD" { int len; char_u *ptr; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0 || find_decl(ptr, len, nchar == 'd', thisblock, SEARCH_START) == FAIL) clearopbeep(oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_SEARCH) && KeyTyped && oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Return TRUE if line[offset] is not inside a C-style comment or string, FALSE * otherwise. */ static int is_ident(char_u *line, int offset) { int i; int incomment = FALSE; int instring = 0; int prev = 0; for (i = 0; i < offset && line[i] != NUL; i++) { if (instring != 0) { if (prev != '\\' && line[i] == instring) instring = 0; } else if ((line[i] == '"' || line[i] == '\'') && !incomment) { instring = line[i]; } else { if (incomment) { if (prev == '*' && line[i] == '/') incomment = FALSE; } else if (prev == '/' && line[i] == '*') { incomment = TRUE; } else if (prev == '/' && line[i] == '/') { return FALSE; } } prev = line[i]; } return incomment == FALSE && instring == 0; } /* * Search for variable declaration of "ptr[len]". * When "locally" is TRUE in the current function ("gd"), otherwise in the * current file ("gD"). * When "thisblock" is TRUE check the {} block scope. * Return FAIL when not found. */ int find_decl( char_u *ptr, int len, int locally, int thisblock, int flags_arg) // flags passed to searchit() { char_u *pat; pos_T old_pos; pos_T par_pos; pos_T found_pos; int t; int save_p_ws; int save_p_scs; int retval = OK; int incll; int searchflags = flags_arg; int valid; if ((pat = alloc(len + 7)) == NULL) return FAIL; // Put "\V" before the pattern to avoid that the special meaning of "." // and "~" causes trouble. sprintf((char *)pat, vim_iswordp(ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s", len, ptr); old_pos = curwin->w_cursor; save_p_ws = p_ws; save_p_scs = p_scs; p_ws = FALSE; // don't wrap around end of file now p_scs = FALSE; // don't switch ignorecase off now /* * With "gD" go to line 1. * With "gd" Search back for the start of the current function, then go * back until a blank line. If this fails go to line 1. */ if (!locally || !findpar(&incll, BACKWARD, 1L, '{', FALSE)) { setpcmark(); // Set in findpar() otherwise curwin->w_cursor.lnum = 1; par_pos = curwin->w_cursor; } else { par_pos = curwin->w_cursor; while (curwin->w_cursor.lnum > 1 && *skipwhite(ml_get_curline()) != NUL) --curwin->w_cursor.lnum; } curwin->w_cursor.col = 0; // Search forward for the identifier, ignore comment lines. CLEAR_POS(&found_pos); for (;;) { t = searchit(curwin, curbuf, &curwin->w_cursor, NULL, FORWARD, pat, 1L, searchflags, RE_LAST, NULL); if (curwin->w_cursor.lnum >= old_pos.lnum) t = FAIL; // match after start is failure too if (thisblock && t != FAIL) { pos_T *pos; // Check that the block the match is in doesn't end before the // position where we started the search from. if ((pos = findmatchlimit(NULL, '}', FM_FORWARD, (int)(old_pos.lnum - curwin->w_cursor.lnum + 1))) != NULL && pos->lnum < old_pos.lnum) { // There can't be a useful match before the end of this block. // Skip to the end. curwin->w_cursor = *pos; continue; } } if (t == FAIL) { // If we previously found a valid position, use it. if (found_pos.lnum != 0) { curwin->w_cursor = found_pos; t = OK; } break; } if (get_leader_len(ml_get_curline(), NULL, FALSE, TRUE) > 0) { // Ignore this line, continue at start of next line. ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; continue; } valid = is_ident(ml_get_curline(), curwin->w_cursor.col); // If the current position is not a valid identifier and a previous // match is present, favor that one instead. if (!valid && found_pos.lnum != 0) { curwin->w_cursor = found_pos; break; } // Global search: use first valid match found if (valid && !locally) break; if (valid && curwin->w_cursor.lnum >= par_pos.lnum) { // If we previously found a valid position, use it. if (found_pos.lnum != 0) curwin->w_cursor = found_pos; break; } // For finding a local variable and the match is before the "{" or // inside a comment, continue searching. For K&R style function // declarations this skips the function header without types. if (!valid) CLEAR_POS(&found_pos); else found_pos = curwin->w_cursor; // Remove SEARCH_START from flags to avoid getting stuck at one // position. searchflags &= ~SEARCH_START; } if (t == FAIL) { retval = FAIL; curwin->w_cursor = old_pos; } else { curwin->w_set_curswant = TRUE; // "n" searches forward now reset_search_dir(); } vim_free(pat); p_ws = save_p_ws; p_scs = save_p_scs; return retval; } /* * Move 'dist' lines in direction 'dir', counting lines by *screen* * lines rather than lines in the file. * 'dist' must be positive. * * Return OK if able to move cursor, FAIL otherwise. */ static int nv_screengo(oparg_T *oap, int dir, long dist) { int linelen = linetabsize(ml_get_curline()); int retval = OK; int atend = FALSE; int n; int col_off1; // margin offset for first screen line int col_off2; // margin offset for wrapped screen line int width1; // text width for first screen line int width2; // test width for wrapped screen line oap->motion_type = MCHAR; oap->inclusive = (curwin->w_curswant == MAXCOL); col_off1 = curwin_col_off(); col_off2 = col_off1 - curwin_col_off2(); width1 = curwin->w_width - col_off1; width2 = curwin->w_width - col_off2; if (width2 == 0) width2 = 1; // avoid divide by zero if (curwin->w_width != 0) { /* * Instead of sticking at the last character of the buffer line we * try to stick in the last column of the screen. */ if (curwin->w_curswant == MAXCOL) { atend = TRUE; validate_virtcol(); if (width1 <= 0) curwin->w_curswant = 0; else { curwin->w_curswant = width1 - 1; if (curwin->w_virtcol > curwin->w_curswant) curwin->w_curswant += ((curwin->w_virtcol - curwin->w_curswant - 1) / width2 + 1) * width2; } } else { if (linelen > width1) n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; else n = width1; if (curwin->w_curswant >= (colnr_T)n) curwin->w_curswant = n - 1; } while (dist--) { if (dir == BACKWARD) { if ((long)curwin->w_curswant >= width1 #ifdef FEAT_FOLDING && !hasFolding(curwin->w_cursor.lnum, NULL, NULL) #endif ) // Move back within the line. This can give a negative value // for w_curswant if width1 < width2 (with cpoptions+=n), // which will get clipped to column 0. curwin->w_curswant -= width2; else { // to previous line #ifdef FEAT_FOLDING // Move to the start of a closed fold. Don't do that when // 'foldopen' contains "all": it will open in a moment. if (!(fdo_flags & FDO_ALL)) (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); #endif if (curwin->w_cursor.lnum == 1) { retval = FAIL; break; } --curwin->w_cursor.lnum; linelen = linetabsize(ml_get_curline()); if (linelen > width1) curwin->w_curswant += (((linelen - width1 - 1) / width2) + 1) * width2; } } else // dir == FORWARD { if (linelen > width1) n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1; else n = width1; if (curwin->w_curswant + width2 < (colnr_T)n #ifdef FEAT_FOLDING && !hasFolding(curwin->w_cursor.lnum, NULL, NULL) #endif ) // move forward within line curwin->w_curswant += width2; else { // to next line #ifdef FEAT_FOLDING // Move to the end of a closed fold. (void)hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum); #endif if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { retval = FAIL; break; } curwin->w_cursor.lnum++; curwin->w_curswant %= width2; // Check if the cursor has moved below the number display // when width1 < width2 (with cpoptions+=n). Subtract width2 // to get a negative value for w_curswant, which will get // clipped to column 0. if (curwin->w_curswant >= width1) curwin->w_curswant -= width2; linelen = linetabsize(ml_get_curline()); } } } } if (virtual_active() && atend) coladvance(MAXCOL); else coladvance(curwin->w_curswant); if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { colnr_T virtcol; /* * Check for landing on a character that got split at the end of the * last line. We want to advance a screenline, not end up in the same * screenline or move two screenlines. */ validate_virtcol(); virtcol = curwin->w_virtcol; #if defined(FEAT_LINEBREAK) if (virtcol > (colnr_T)width1 && *get_showbreak_value(curwin) != NUL) virtcol -= vim_strsize(get_showbreak_value(curwin)); #endif if (virtcol > curwin->w_curswant && (curwin->w_curswant < (colnr_T)width1 ? (curwin->w_curswant > (colnr_T)width1 / 2) : ((curwin->w_curswant - width1) % width2 > (colnr_T)width2 / 2))) --curwin->w_cursor.col; } if (atend) curwin->w_curswant = MAXCOL; // stick in the last column return retval; } /* * Handle CTRL-E and CTRL-Y commands: scroll a line up or down. * cap->arg must be TRUE for CTRL-E. */ void nv_scroll_line(cmdarg_T *cap) { if (!checkclearop(cap->oap)) scroll_redraw(cap->arg, cap->count1); } /* * Scroll "count" lines up or down, and redraw. */ void scroll_redraw(int up, long count) { linenr_T prev_topline = curwin->w_topline; #ifdef FEAT_DIFF int prev_topfill = curwin->w_topfill; #endif linenr_T prev_lnum = curwin->w_cursor.lnum; if (up) scrollup(count, TRUE); else scrolldown(count, TRUE); if (get_scrolloff_value()) { // Adjust the cursor position for 'scrolloff'. Mark w_topline as // valid, otherwise the screen jumps back at the end of the file. cursor_correct(); check_cursor_moved(curwin); curwin->w_valid |= VALID_TOPLINE; // If moved back to where we were, at least move the cursor, otherwise // we get stuck at one position. Don't move the cursor up if the // first line of the buffer is already on the screen while (curwin->w_topline == prev_topline #ifdef FEAT_DIFF && curwin->w_topfill == prev_topfill #endif ) { if (up) { if (curwin->w_cursor.lnum > prev_lnum || cursor_down(1L, FALSE) == FAIL) break; } else { if (curwin->w_cursor.lnum < prev_lnum || prev_topline == 1L || cursor_up(1L, FALSE) == FAIL) break; } // Mark w_topline as valid, otherwise the screen jumps back at the // end of the file. check_cursor_moved(curwin); curwin->w_valid |= VALID_TOPLINE; } } if (curwin->w_cursor.lnum != prev_lnum) coladvance(curwin->w_curswant); redraw_later(VALID); } /* * Commands that start with "z". */ static void nv_zet(cmdarg_T *cap) { long n; colnr_T col; int nchar = cap->nchar; #ifdef FEAT_FOLDING long old_fdl = curwin->w_p_fdl; int old_fen = curwin->w_p_fen; #endif #ifdef FEAT_SPELL int undo = FALSE; #endif long siso = get_sidescrolloff_value(); if (VIM_ISDIGIT(nchar)) { /* * "z123{nchar}": edit the count before obtaining {nchar} */ if (checkclearop(cap->oap)) return; n = nchar - '0'; for (;;) { #ifdef USE_ON_FLY_SCROLL dont_scroll = TRUE; // disallow scrolling here #endif ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes nchar = plain_vgetc(); LANGMAP_ADJUST(nchar, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO (void)add_to_showcmd(nchar); #endif if (nchar == K_DEL || nchar == K_KDEL) n /= 10; else if (VIM_ISDIGIT(nchar)) n = n * 10 + (nchar - '0'); else if (nchar == CAR) { #ifdef FEAT_GUI need_mouse_correct = TRUE; #endif win_setheight((int)n); break; } else if (nchar == 'l' || nchar == 'h' || nchar == K_LEFT || nchar == K_RIGHT) { cap->count1 = n ? n * cap->count1 : cap->count1; goto dozet; } else { clearopbeep(cap->oap); break; } } cap->oap->op_type = OP_NOP; return; } dozet: if ( #ifdef FEAT_FOLDING // "zf" and "zF" are always an operator, "zd", "zo", "zO", "zc" // and "zC" only in Visual mode. "zj" and "zk" are motion // commands. cap->nchar != 'f' && cap->nchar != 'F' && !(VIsual_active && vim_strchr((char_u *)"dcCoO", cap->nchar)) && cap->nchar != 'j' && cap->nchar != 'k' && #endif checkclearop(cap->oap)) return; /* * For "z+", "z<CR>", "zt", "z.", "zz", "z^", "z-", "zb": * If line number given, set cursor. */ if ((vim_strchr((char_u *)"+\r\nt.z^-b", nchar) != NULL) && cap->count0 && cap->count0 != curwin->w_cursor.lnum) { setpcmark(); if (cap->count0 > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; else curwin->w_cursor.lnum = cap->count0; check_cursor_col(); } switch (nchar) { // "z+", "z<CR>" and "zt": put cursor at top of screen case '+': if (cap->count0 == 0) { // No count given: put cursor at the line below screen validate_botline(); // make sure w_botline is valid if (curwin->w_botline > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; else curwin->w_cursor.lnum = curwin->w_botline; } // FALLTHROUGH case NL: case CAR: case K_KENTER: beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 't': scroll_cursor_top(0, TRUE); redraw_later(VALID); set_fraction(curwin); break; // "z." and "zz": put cursor in middle of screen case '.': beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 'z': scroll_cursor_halfway(TRUE); redraw_later(VALID); set_fraction(curwin); break; // "z^", "z-" and "zb": put cursor at bottom of screen case '^': // Strange Vi behavior: <count>z^ finds line at top of window // when <count> is at bottom of window, and puts that one at // bottom of window. if (cap->count0 != 0) { scroll_cursor_bot(0, TRUE); curwin->w_cursor.lnum = curwin->w_topline; } else if (curwin->w_topline == 1) curwin->w_cursor.lnum = 1; else curwin->w_cursor.lnum = curwin->w_topline - 1; // FALLTHROUGH case '-': beginline(BL_WHITE | BL_FIX); // FALLTHROUGH case 'b': scroll_cursor_bot(0, TRUE); redraw_later(VALID); set_fraction(curwin); break; // "zH" - scroll screen right half-page case 'H': cap->count1 *= curwin->w_width / 2; // FALLTHROUGH // "zh" - scroll screen to the right case 'h': case K_LEFT: if (!curwin->w_p_wrap) { if ((colnr_T)cap->count1 > curwin->w_leftcol) curwin->w_leftcol = 0; else curwin->w_leftcol -= (colnr_T)cap->count1; leftcol_changed(); } break; // "zL" - scroll screen left half-page case 'L': cap->count1 *= curwin->w_width / 2; // FALLTHROUGH // "zl" - scroll screen to the left case 'l': case K_RIGHT: if (!curwin->w_p_wrap) { // scroll the window left curwin->w_leftcol += (colnr_T)cap->count1; leftcol_changed(); } break; // "zs" - scroll screen, cursor at the start case 's': if (!curwin->w_p_wrap) { #ifdef FEAT_FOLDING if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) col = 0; // like the cursor is in col 0 else #endif getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL); if ((long)col > siso) col -= siso; else col = 0; if (curwin->w_leftcol != col) { curwin->w_leftcol = col; redraw_later(NOT_VALID); } } break; // "ze" - scroll screen, cursor at the end case 'e': if (!curwin->w_p_wrap) { #ifdef FEAT_FOLDING if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) col = 0; // like the cursor is in col 0 else #endif getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col); n = curwin->w_width - curwin_col_off(); if ((long)col + siso < n) col = 0; else col = col + siso - n + 1; if (curwin->w_leftcol != col) { curwin->w_leftcol = col; redraw_later(NOT_VALID); } } break; // "zp", "zP" in block mode put without addind trailing spaces case 'P': case 'p': nv_put(cap); break; // "zy" Yank without trailing spaces case 'y': nv_operator(cap); break; #ifdef FEAT_FOLDING // "zF": create fold command // "zf": create fold operator case 'F': case 'f': if (foldManualAllowed(TRUE)) { cap->nchar = 'f'; nv_operator(cap); curwin->w_p_fen = TRUE; // "zF" is like "zfzf" if (nchar == 'F' && cap->oap->op_type == OP_FOLD) { nv_operator(cap); finish_op = TRUE; } } else clearopbeep(cap->oap); break; // "zd": delete fold at cursor // "zD": delete fold at cursor recursively case 'd': case 'D': if (foldManualAllowed(FALSE)) { if (VIsual_active) nv_operator(cap); else deleteFold(curwin->w_cursor.lnum, curwin->w_cursor.lnum, nchar == 'D', FALSE); } break; // "zE": erase all folds case 'E': if (foldmethodIsManual(curwin)) { clearFolding(curwin); changed_window_setting(); } else if (foldmethodIsMarker(curwin)) deleteFold((linenr_T)1, curbuf->b_ml.ml_line_count, TRUE, FALSE); else emsg(_("E352: Cannot erase folds with current 'foldmethod'")); break; // "zn": fold none: reset 'foldenable' case 'n': curwin->w_p_fen = FALSE; break; // "zN": fold Normal: set 'foldenable' case 'N': curwin->w_p_fen = TRUE; break; // "zi": invert folding: toggle 'foldenable' case 'i': curwin->w_p_fen = !curwin->w_p_fen; break; // "za": open closed fold or close open fold at cursor case 'a': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) openFold(curwin->w_cursor.lnum, cap->count1); else { closeFold(curwin->w_cursor.lnum, cap->count1); curwin->w_p_fen = TRUE; } break; // "zA": open fold at cursor recursively case 'A': if (hasFolding(curwin->w_cursor.lnum, NULL, NULL)) openFoldRecurse(curwin->w_cursor.lnum); else { closeFoldRecurse(curwin->w_cursor.lnum); curwin->w_p_fen = TRUE; } break; // "zo": open fold at cursor or Visual area case 'o': if (VIsual_active) nv_operator(cap); else openFold(curwin->w_cursor.lnum, cap->count1); break; // "zO": open fold recursively case 'O': if (VIsual_active) nv_operator(cap); else openFoldRecurse(curwin->w_cursor.lnum); break; // "zc": close fold at cursor or Visual area case 'c': if (VIsual_active) nv_operator(cap); else closeFold(curwin->w_cursor.lnum, cap->count1); curwin->w_p_fen = TRUE; break; // "zC": close fold recursively case 'C': if (VIsual_active) nv_operator(cap); else closeFoldRecurse(curwin->w_cursor.lnum); curwin->w_p_fen = TRUE; break; // "zv": open folds at the cursor case 'v': foldOpenCursor(); break; // "zx": re-apply 'foldlevel' and open folds at the cursor case 'x': curwin->w_p_fen = TRUE; curwin->w_foldinvalid = TRUE; // recompute folds newFoldLevel(); // update right now foldOpenCursor(); break; // "zX": undo manual opens/closes, re-apply 'foldlevel' case 'X': curwin->w_p_fen = TRUE; curwin->w_foldinvalid = TRUE; // recompute folds old_fdl = -1; // force an update break; // "zm": fold more case 'm': if (curwin->w_p_fdl > 0) { curwin->w_p_fdl -= cap->count1; if (curwin->w_p_fdl < 0) curwin->w_p_fdl = 0; } old_fdl = -1; // force an update curwin->w_p_fen = TRUE; break; // "zM": close all folds case 'M': curwin->w_p_fdl = 0; old_fdl = -1; // force an update curwin->w_p_fen = TRUE; break; // "zr": reduce folding case 'r': curwin->w_p_fdl += cap->count1; { int d = getDeepestNesting(); if (curwin->w_p_fdl >= d) curwin->w_p_fdl = d; } break; // "zR": open all folds case 'R': curwin->w_p_fdl = getDeepestNesting(); old_fdl = -1; // force an update break; case 'j': // "zj" move to next fold downwards case 'k': // "zk" move to next fold upwards if (foldMoveTo(TRUE, nchar == 'j' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); break; #endif // FEAT_FOLDING #ifdef FEAT_SPELL case 'u': // "zug" and "zuw": undo "zg" and "zw" ++no_mapping; ++allow_keys; // no mapping for nchar, but allow key codes nchar = plain_vgetc(); LANGMAP_ADJUST(nchar, TRUE); --no_mapping; --allow_keys; #ifdef FEAT_CMDL_INFO (void)add_to_showcmd(nchar); #endif if (vim_strchr((char_u *)"gGwW", nchar) == NULL) { clearopbeep(cap->oap); break; } undo = TRUE; // FALLTHROUGH case 'g': // "zg": add good word to word list case 'w': // "zw": add wrong word to word list case 'G': // "zG": add good word to temp word list case 'W': // "zW": add wrong word to temp word list { char_u *ptr = NULL; int len; if (checkclearop(cap->oap)) break; if (VIsual_active && get_visual_text(cap, &ptr, &len) == FAIL) return; if (ptr == NULL) { pos_T pos = curwin->w_cursor; // Find bad word under the cursor. When 'spell' is // off this fails and find_ident_under_cursor() is // used below. emsg_off++; len = spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL); emsg_off--; if (len != 0 && curwin->w_cursor.col <= pos.col) ptr = ml_get_pos(&curwin->w_cursor); curwin->w_cursor = pos; } if (ptr == NULL && (len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) return; spell_add_word(ptr, len, nchar == 'w' || nchar == 'W' ? SPELL_ADD_BAD : SPELL_ADD_GOOD, (nchar == 'G' || nchar == 'W') ? 0 : (int)cap->count1, undo); } break; case '=': // "z=": suggestions for a badly spelled word if (!checkclearop(cap->oap)) spell_suggest((int)cap->count0); break; #endif default: clearopbeep(cap->oap); } #ifdef FEAT_FOLDING // Redraw when 'foldenable' changed if (old_fen != curwin->w_p_fen) { # ifdef FEAT_DIFF win_T *wp; if (foldmethodIsDiff(curwin) && curwin->w_p_scb) { // Adjust 'foldenable' in diff-synced windows. FOR_ALL_WINDOWS(wp) { if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb) { wp->w_p_fen = curwin->w_p_fen; changed_window_setting_win(wp); } } } # endif changed_window_setting(); } // Redraw when 'foldlevel' changed. if (old_fdl != curwin->w_p_fdl) newFoldLevel(); #endif } #ifdef FEAT_GUI /* * Vertical scrollbar movement. */ static void nv_ver_scrollbar(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to scroll gui_do_scroll(); } /* * Horizontal scrollbar movement. */ static void nv_hor_scrollbar(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to scroll gui_do_horiz_scroll(scrollbar_value, FALSE); } #endif #if defined(FEAT_GUI_TABLINE) || defined(PROTO) /* * Click in GUI tab. */ static void nv_tabline(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to jump tabs. goto_tabpage(current_tab); } /* * Selected item in tab line menu. */ static void nv_tabmenu(cmdarg_T *cap) { if (cap->oap->op_type != OP_NOP) clearopbeep(cap->oap); // Even if an operator was pending, we still want to jump tabs. handle_tabmenu(); } /* * Handle selecting an item of the GUI tab line menu. * Used in Normal and Insert mode. */ void handle_tabmenu(void) { switch (current_tabmenu) { case TABLINE_MENU_CLOSE: if (current_tab == 0) do_cmdline_cmd((char_u *)"tabclose"); else { vim_snprintf((char *)IObuff, IOSIZE, "tabclose %d", current_tab); do_cmdline_cmd(IObuff); } break; case TABLINE_MENU_NEW: if (current_tab == 0) do_cmdline_cmd((char_u *)"$tabnew"); else { vim_snprintf((char *)IObuff, IOSIZE, "%dtabnew", current_tab - 1); do_cmdline_cmd(IObuff); } break; case TABLINE_MENU_OPEN: if (current_tab == 0) do_cmdline_cmd((char_u *)"browse $tabnew"); else { vim_snprintf((char *)IObuff, IOSIZE, "browse %dtabnew", current_tab - 1); do_cmdline_cmd(IObuff); } break; } } #endif /* * "Q" command. */ static void nv_exmode(cmdarg_T *cap) { /* * Ignore 'Q' in Visual mode, just give a beep. */ if (VIsual_active) vim_beep(BO_EX); else if (!checkclearop(cap->oap)) do_exmode(FALSE); } /* * Handle a ":" command. */ static void nv_colon(cmdarg_T *cap) { int old_p_im; int cmd_result; int is_cmdkey = cap->cmdchar == K_COMMAND; if (VIsual_active && !is_cmdkey) nv_operator(cap); else { if (cap->oap->op_type != OP_NOP) { // Using ":" as a movement is characterwise exclusive. cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; } else if (cap->count0 && !is_cmdkey) { // translate "count:" into ":.,.+(count - 1)" stuffcharReadbuff('.'); if (cap->count0 > 1) { stuffReadbuff((char_u *)",.+"); stuffnumReadbuff((long)cap->count0 - 1L); } } // When typing, don't type below an old message if (KeyTyped) compute_cmdrow(); old_p_im = p_im; // get a command line and execute it cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL, cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0); // If 'insertmode' changed, enter or exit Insert mode if (p_im != old_p_im) { if (p_im) restart_edit = 'i'; else restart_edit = 0; } if (cmd_result == FAIL) // The Ex command failed, do not execute the operator. clearop(cap->oap); else if (cap->oap->op_type != OP_NOP && (cap->oap->start.lnum > curbuf->b_ml.ml_line_count || cap->oap->start.col > (colnr_T)STRLEN(ml_get(cap->oap->start.lnum)) || did_emsg )) // The start of the operator has become invalid by the Ex command. clearopbeep(cap->oap); } } /* * Handle CTRL-G command. */ static void nv_ctrlg(cmdarg_T *cap) { if (VIsual_active) // toggle Selection/Visual mode { VIsual_select = !VIsual_select; showmode(); } else if (!checkclearop(cap->oap)) // print full name if count given or :cd used fileinfo((int)cap->count0, FALSE, TRUE); } /* * Handle CTRL-H <Backspace> command. */ static void nv_ctrlh(cmdarg_T *cap) { if (VIsual_active && VIsual_select) { cap->cmdchar = 'x'; // BS key behaves like 'x' in Select mode v_visop(cap); } else nv_left(cap); } /* * CTRL-L: clear screen and redraw. */ static void nv_clear(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { #ifdef FEAT_SYN_HL // Clear all syntax states to force resyncing. syn_stack_free_all(curwin->w_s); # ifdef FEAT_RELTIME { win_T *wp; FOR_ALL_WINDOWS(wp) wp->w_s->b_syn_slow = FALSE; } # endif #endif redraw_later(CLEAR); #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL)) # ifdef VIMDLL if (!gui.in_use) # endif resize_console_buf(); #endif } } /* * CTRL-O: In Select mode: switch to Visual mode for one command. * Otherwise: Go to older pcmark. */ static void nv_ctrlo(cmdarg_T *cap) { if (VIsual_active && VIsual_select) { VIsual_select = FALSE; showmode(); restart_VIsual_select = 2; // restart Select mode later } else { cap->count1 = -cap->count1; nv_pcmark(cap); } } /* * CTRL-^ command, short for ":e #". Works even when the alternate buffer is * not named. */ static void nv_hat(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) (void)buflist_getfile((int)cap->count0, (linenr_T)0, GETF_SETMARK|GETF_ALT, FALSE); } /* * "Z" commands. */ static void nv_Zet(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { switch (cap->nchar) { // "ZZ": equivalent to ":x". case 'Z': do_cmdline_cmd((char_u *)"x"); break; // "ZQ": equivalent to ":q!" (Elvis compatible). case 'Q': do_cmdline_cmd((char_u *)"q!"); break; default: clearopbeep(cap->oap); } } } /* * Call nv_ident() as if "c1" was used, with "c2" as next character. */ void do_nv_ident(int c1, int c2) { oparg_T oa; cmdarg_T ca; clear_oparg(&oa); CLEAR_FIELD(ca); ca.oap = &oa; ca.cmdchar = c1; ca.nchar = c2; nv_ident(&ca); } /* * Handle the commands that use the word under the cursor. * [g] CTRL-] :ta to current identifier * [g] 'K' run program for current identifier * [g] '*' / to current identifier or string * [g] '#' ? to current identifier or string * g ']' :tselect for current identifier */ static void nv_ident(cmdarg_T *cap) { char_u *ptr = NULL; char_u *buf; unsigned buflen; char_u *newbuf; char_u *p; char_u *kp; // value of 'keywordprg' int kp_help; // 'keywordprg' is ":he" int kp_ex; // 'keywordprg' starts with ":" int n = 0; // init for GCC int cmdchar; int g_cmd; // "g" command int tag_cmd = FALSE; char_u *aux_ptr; int isman; int isman_s; if (cap->cmdchar == 'g') // "g*", "g#", "g]" and "gCTRL-]" { cmdchar = cap->nchar; g_cmd = TRUE; } else { cmdchar = cap->cmdchar; g_cmd = FALSE; } if (cmdchar == POUND) // the pound sign, '#' for English keyboards cmdchar = '#'; /* * The "]", "CTRL-]" and "K" commands accept an argument in Visual mode. */ if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K') { if (VIsual_active && get_visual_text(cap, &ptr, &n) == FAIL) return; if (checkclearopq(cap->oap)) return; } if (ptr == NULL && (n = find_ident_under_cursor(&ptr, (cmdchar == '*' || cmdchar == '#') ? FIND_IDENT|FIND_STRING : FIND_IDENT)) == 0) { clearop(cap->oap); return; } // Allocate buffer to put the command in. Inserting backslashes can // double the length of the word. p_kp / curbuf->b_p_kp could be added // and some numbers. kp = (*curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp); kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0 || STRCMP(kp, ":help") == 0); if (kp_help && *skipwhite(ptr) == NUL) { emsg(_(e_noident)); // found white space only return; } kp_ex = (*kp == ':'); buflen = (unsigned)(n * 2 + 30 + STRLEN(kp)); buf = alloc(buflen); if (buf == NULL) return; buf[0] = NUL; switch (cmdchar) { case '*': case '#': /* * Put cursor at start of word, makes search skip the word * under the cursor. * Call setpcmark() first, so "*``" puts the cursor back where * it was. */ setpcmark(); curwin->w_cursor.col = (colnr_T) (ptr - ml_get_curline()); if (!g_cmd && vim_iswordp(ptr)) STRCPY(buf, "\\<"); no_smartcase = TRUE; // don't use 'smartcase' now break; case 'K': if (kp_help) STRCPY(buf, "he! "); else if (kp_ex) { if (cap->count0 != 0) vim_snprintf((char *)buf, buflen, "%s %ld", kp, cap->count0); else STRCPY(buf, kp); STRCAT(buf, " "); } else { // An external command will probably use an argument starting // with "-" as an option. To avoid trouble we skip the "-". while (*ptr == '-' && n > 0) { ++ptr; --n; } if (n == 0) { emsg(_(e_noident)); // found dashes only vim_free(buf); return; } // When a count is given, turn it into a range. Is this // really what we want? isman = (STRCMP(kp, "man") == 0); isman_s = (STRCMP(kp, "man -s") == 0); if (cap->count0 != 0 && !(isman || isman_s)) sprintf((char *)buf, ".,.+%ld", cap->count0 - 1); STRCAT(buf, "! "); if (cap->count0 == 0 && isman_s) STRCAT(buf, "man"); else STRCAT(buf, kp); STRCAT(buf, " "); if (cap->count0 != 0 && (isman || isman_s)) { sprintf((char *)buf + STRLEN(buf), "%ld", cap->count0); STRCAT(buf, " "); } } break; case ']': tag_cmd = TRUE; #ifdef FEAT_CSCOPE if (p_cst) STRCPY(buf, "cstag "); else #endif STRCPY(buf, "ts "); break; default: tag_cmd = TRUE; if (curbuf->b_help) STRCPY(buf, "he! "); else { if (g_cmd) STRCPY(buf, "tj "); else if (cap->count0 == 0) STRCPY(buf, "ta "); else sprintf((char *)buf, ":%ldta ", cap->count0); } } /* * Now grab the chars in the identifier */ if (cmdchar == 'K' && !kp_help) { ptr = vim_strnsave(ptr, n); if (kp_ex) // Escape the argument properly for an Ex command p = vim_strsave_fnameescape(ptr, FALSE); else // Escape the argument properly for a shell command p = vim_strsave_shellescape(ptr, TRUE, TRUE); vim_free(ptr); if (p == NULL) { vim_free(buf); return; } newbuf = vim_realloc(buf, STRLEN(buf) + STRLEN(p) + 1); if (newbuf == NULL) { vim_free(buf); vim_free(p); return; } buf = newbuf; STRCAT(buf, p); vim_free(p); } else { if (cmdchar == '*') aux_ptr = (char_u *)(magic_isset() ? "/.*~[^$\\" : "/^$\\"); else if (cmdchar == '#') aux_ptr = (char_u *)(magic_isset() ? "/?.*~[^$\\" : "/?^$\\"); else if (tag_cmd) { if (curbuf->b_help) // ":help" handles unescaped argument aux_ptr = (char_u *)""; else aux_ptr = (char_u *)"\\|\"\n["; } else aux_ptr = (char_u *)"\\|\"\n*?["; p = buf + STRLEN(buf); while (n-- > 0) { // put a backslash before \ and some others if (vim_strchr(aux_ptr, *ptr) != NULL) *p++ = '\\'; // When current byte is a part of multibyte character, copy all // bytes of that character. if (has_mbyte) { int i; int len = (*mb_ptr2len)(ptr) - 1; for (i = 0; i < len && n >= 1; ++i, --n) *p++ = *ptr++; } *p++ = *ptr++; } *p = NUL; } /* * Execute the command. */ if (cmdchar == '*' || cmdchar == '#') { if (!g_cmd && (has_mbyte ? vim_iswordp(mb_prevptr(ml_get_curline(), ptr)) : vim_iswordc(ptr[-1]))) STRCAT(buf, "\\>"); // put pattern in search history init_history(); add_to_history(HIST_SEARCH, buf, TRUE, NUL); (void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL); } else { g_tag_at_cursor = TRUE; do_cmdline_cmd(buf); g_tag_at_cursor = FALSE; } vim_free(buf); } /* * Get visually selected text, within one line only. * Returns FAIL if more than one line selected. */ int get_visual_text( cmdarg_T *cap, char_u **pp, // return: start of selected text int *lenp) // return: length of selected text { if (VIsual_mode != 'V') unadjust_for_sel(); if (VIsual.lnum != curwin->w_cursor.lnum) { if (cap != NULL) clearopbeep(cap->oap); return FAIL; } if (VIsual_mode == 'V') { *pp = ml_get_curline(); *lenp = (int)STRLEN(*pp); } else { if (LT_POS(curwin->w_cursor, VIsual)) { *pp = ml_get_pos(&curwin->w_cursor); *lenp = VIsual.col - curwin->w_cursor.col + 1; } else { *pp = ml_get_pos(&VIsual); *lenp = curwin->w_cursor.col - VIsual.col + 1; } if (has_mbyte) // Correct the length to include the whole last character. *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1; } reset_VIsual_and_resel(); return OK; } /* * CTRL-T: backwards in tag stack */ static void nv_tagpop(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) do_tag((char_u *)"", DT_POP, (int)cap->count1, FALSE, TRUE); } /* * Handle scrolling command 'H', 'L' and 'M'. */ static void nv_scroll(cmdarg_T *cap) { int used = 0; long n; #ifdef FEAT_FOLDING linenr_T lnum; #endif int half; cap->oap->motion_type = MLINE; setpcmark(); if (cap->cmdchar == 'L') { validate_botline(); // make sure curwin->w_botline is valid curwin->w_cursor.lnum = curwin->w_botline - 1; if (cap->count1 - 1 >= curwin->w_cursor.lnum) curwin->w_cursor.lnum = 1; else { #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { // Count a fold for one screen line. for (n = cap->count1 - 1; n > 0 && curwin->w_cursor.lnum > curwin->w_topline; --n) { (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); --curwin->w_cursor.lnum; } } else #endif curwin->w_cursor.lnum -= cap->count1 - 1; } } else { if (cap->cmdchar == 'M') { #ifdef FEAT_DIFF // Don't count filler lines above the window. used -= diff_check_fill(curwin, curwin->w_topline) - curwin->w_topfill; #endif validate_botline(); // make sure w_empty_rows is valid half = (curwin->w_height - curwin->w_empty_rows + 1) / 2; for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; ++n) { #ifdef FEAT_DIFF // Count half he number of filler lines to be "below this // line" and half to be "above the next line". if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline + n) / 2 >= half) { --n; break; } #endif used += plines(curwin->w_topline + n); if (used >= half) break; #ifdef FEAT_FOLDING if (hasFolding(curwin->w_topline + n, NULL, &lnum)) n = lnum - curwin->w_topline; #endif } if (n > 0 && used > curwin->w_height) --n; } else // (cap->cmdchar == 'H') { n = cap->count1 - 1; #ifdef FEAT_FOLDING if (hasAnyFolding(curwin)) { // Count a fold for one screen line. lnum = curwin->w_topline; while (n-- > 0 && lnum < curwin->w_botline - 1) { (void)hasFolding(lnum, NULL, &lnum); ++lnum; } n = lnum - curwin->w_topline; } #endif } curwin->w_cursor.lnum = curwin->w_topline + n; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; } // Correct for 'so', except when an operator is pending. if (cap->oap->op_type == OP_NOP) cursor_correct(); beginline(BL_SOL | BL_FIX); } /* * Cursor right commands. */ static void nv_right(cmdarg_T *cap) { long n; int past_line; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { // <C-Right> and <S-Right> move a word or WORD right if (mod_mask & MOD_MASK_CTRL) cap->arg = TRUE; nv_wordcmd(cap); return; } cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; past_line = (VIsual_active && *p_sel != 'o'); /* * In virtual edit mode, there's no such thing as "past_line", as lines * are (theoretically) infinitely long. */ if (virtual_active()) past_line = 0; for (n = cap->count1; n > 0; --n) { if ((!past_line && oneright() == FAIL) || (past_line && *ml_get_cursor() == NUL) ) { /* * <Space> wraps to next line if 'whichwrap' has 's'. * 'l' wraps to next line if 'whichwrap' has 'l'. * CURS_RIGHT wraps to next line if 'whichwrap' has '>'. */ if ( ((cap->cmdchar == ' ' && vim_strchr(p_ww, 's') != NULL) || (cap->cmdchar == 'l' && vim_strchr(p_ww, 'l') != NULL) || (cap->cmdchar == K_RIGHT && vim_strchr(p_ww, '>') != NULL)) && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { // When deleting we also count the NL as a character. // Set cap->oap->inclusive when last char in the line is // included, move to next line after that if ( cap->oap->op_type != OP_NOP && !cap->oap->inclusive && !LINEEMPTY(curwin->w_cursor.lnum)) cap->oap->inclusive = TRUE; else { ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; curwin->w_set_curswant = TRUE; cap->oap->inclusive = FALSE; } continue; } if (cap->oap->op_type == OP_NOP) { // Only beep and flush if not moved at all if (n == cap->count1) beep_flush(); } else { if (!LINEEMPTY(curwin->w_cursor.lnum)) cap->oap->inclusive = TRUE; } break; } else if (past_line) { curwin->w_set_curswant = TRUE; if (virtual_active()) oneright(); else { if (has_mbyte) curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor()); else ++curwin->w_cursor.col; } } } #ifdef FEAT_FOLDING if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Cursor left commands. * * Returns TRUE when operator end should not be adjusted. */ static void nv_left(cmdarg_T *cap) { long n; if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) { // <C-Left> and <S-Left> move a word or WORD left if (mod_mask & MOD_MASK_CTRL) cap->arg = 1; nv_bck_word(cap); return; } cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; for (n = cap->count1; n > 0; --n) { if (oneleft() == FAIL) { // <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'. // 'h' wraps to previous line if 'whichwrap' has 'h'. // CURS_LEFT wraps to previous line if 'whichwrap' has '<'. if ( (((cap->cmdchar == K_BS || cap->cmdchar == Ctrl_H) && vim_strchr(p_ww, 'b') != NULL) || (cap->cmdchar == 'h' && vim_strchr(p_ww, 'h') != NULL) || (cap->cmdchar == K_LEFT && vim_strchr(p_ww, '<') != NULL)) && curwin->w_cursor.lnum > 1) { --(curwin->w_cursor.lnum); coladvance((colnr_T)MAXCOL); curwin->w_set_curswant = TRUE; // When the NL before the first char has to be deleted we // put the cursor on the NUL after the previous line. // This is a very special case, be careful! // Don't adjust op_end now, otherwise it won't work. if ( (cap->oap->op_type == OP_DELETE || cap->oap->op_type == OP_CHANGE) && !LINEEMPTY(curwin->w_cursor.lnum)) { char_u *cp = ml_get_cursor(); if (*cp != NUL) { if (has_mbyte) curwin->w_cursor.col += (*mb_ptr2len)(cp); else ++curwin->w_cursor.col; } cap->retval |= CA_NO_ADJ_OP_END; } continue; } // Only beep and flush if not moved at all else if (cap->oap->op_type == OP_NOP && n == cap->count1) beep_flush(); break; } } #ifdef FEAT_FOLDING if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Cursor up commands. * cap->arg is TRUE for "-": Move cursor to first non-blank. */ static void nv_up(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { // <S-Up> is page up cap->arg = BACKWARD; nv_page(cap); } else { cap->oap->motion_type = MLINE; if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if (cap->arg) beginline(BL_WHITE | BL_FIX); } } /* * Cursor down commands. * cap->arg is TRUE for CR and "+": Move cursor to first non-blank. */ static void nv_down(cmdarg_T *cap) { if (mod_mask & MOD_MASK_SHIFT) { // <S-Down> is page down cap->arg = FORWARD; nv_page(cap); } #if defined(FEAT_QUICKFIX) // Quickfix window only: view the result under the cursor. else if (bt_quickfix(curbuf) && cap->cmdchar == CAR) qf_view_result(FALSE); #endif else { #ifdef FEAT_CMDWIN // In the cmdline window a <CR> executes the command. if (cmdwin_type != 0 && cap->cmdchar == CAR) cmdwin_result = CAR; else #endif #ifdef FEAT_JOB_CHANNEL // In a prompt buffer a <CR> in the last line invokes the callback. if (bt_prompt(curbuf) && cap->cmdchar == CAR && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) { invoke_prompt_callback(); if (restart_edit == 0) restart_edit = 'a'; } else #endif { cap->oap->motion_type = MLINE; if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if (cap->arg) beginline(BL_WHITE | BL_FIX); } } } #ifdef FEAT_SEARCHPATH /* * Grab the file name under the cursor and edit it. */ static void nv_gotofile(cmdarg_T *cap) { char_u *ptr; linenr_T lnum = -1; if (text_locked()) { clearopbeep(cap->oap); text_locked_msg(); return; } if (curbuf_locked()) { clearop(cap->oap); return; } #ifdef FEAT_PROP_POPUP if (ERROR_IF_TERM_POPUP_WINDOW) return; #endif ptr = grab_file_name(cap->count1, &lnum); if (ptr != NULL) { // do autowrite if necessary if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !buf_hide(curbuf)) (void)autowrite(curbuf, FALSE); setpcmark(); if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST, buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK && cap->nchar == 'F' && lnum >= 0) { curwin->w_cursor.lnum = lnum; check_cursor_lnum(); beginline(BL_SOL | BL_FIX); } vim_free(ptr); } else clearop(cap->oap); } #endif /* * <End> command: to end of current line or last line. */ static void nv_end(cmdarg_T *cap) { if (cap->arg || (mod_mask & MOD_MASK_CTRL)) // CTRL-END = goto last line { cap->arg = TRUE; nv_goto(cap); cap->count1 = 1; // to end of current line } nv_dollar(cap); } /* * Handle the "$" command. */ static void nv_dollar(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = TRUE; // In virtual mode when off the edge of a line and an operator // is pending (whew!) keep the cursor where it is. // Otherwise, send it to the end of the line. if (!virtual_active() || gchar_cursor() != NUL || cap->oap->op_type == OP_NOP) curwin->w_curswant = MAXCOL; // so we stay at the end if (cursor_down((long)(cap->count1 - 1), cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Implementation of '?' and '/' commands. * If cap->arg is TRUE don't set PC mark. */ static void nv_search(cmdarg_T *cap) { oparg_T *oap = cap->oap; pos_T save_cursor = curwin->w_cursor; if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13) { // Translate "g??" to "g?g?" cap->cmdchar = 'g'; cap->nchar = '?'; nv_operator(cap); return; } // When using 'incsearch' the cursor may be moved to set a different search // start position. cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0, TRUE); if (cap->searchbuf == NULL) { clearop(oap); return; } (void)normal_search(cap, cap->cmdchar, cap->searchbuf, (cap->arg || !EQUAL_POS(save_cursor, curwin->w_cursor)) ? 0 : SEARCH_MARK, NULL); } /* * Handle "N" and "n" commands. * cap->arg is SEARCH_REV for "N", 0 for "n". */ static void nv_next(cmdarg_T *cap) { pos_T old = curwin->w_cursor; int wrapped = FALSE; int i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, &wrapped); if (i == 1 && !wrapped && EQUAL_POS(old, curwin->w_cursor)) { // Avoid getting stuck on the current cursor position, which can // happen when an offset is given and the cursor is on the last char // in the buffer: Repeat with count + 1. cap->count1 += 1; (void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, NULL); cap->count1 -= 1; } } /* * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat). * Uses only cap->count1 and cap->oap from "cap". * Return 0 for failure, 1 for found, 2 for found and line offset added. */ static int normal_search( cmdarg_T *cap, int dir, char_u *pat, int opt, // extra flags for do_search() int *wrapped) { int i; searchit_arg_T sia; cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; cap->oap->use_reg_one = TRUE; curwin->w_set_curswant = TRUE; CLEAR_FIELD(sia); i = do_search(cap->oap, dir, dir, pat, cap->count1, opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, &sia); if (wrapped != NULL) *wrapped = sia.sa_wrapped; if (i == 0) clearop(cap->oap); else { if (i == 2) cap->oap->motion_type = MLINE; curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) foldOpenCursor(); #endif } // "/$" will put the cursor after the end of the line, may need to // correct that here check_cursor(); return i; } /* * Character search commands. * cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for * ',' and FALSE for ';'. * cap->nchar is NUL for ',' and ';' (repeat the search) */ static void nv_csearch(cmdarg_T *cap) { int t_cmd; if (cap->cmdchar == 't' || cap->cmdchar == 'T') t_cmd = TRUE; else t_cmd = FALSE; cap->oap->motion_type = MCHAR; if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL) clearopbeep(cap->oap); else { curwin->w_set_curswant = TRUE; // Include a Tab for "tx" and for "dfx". if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD && (t_cmd || cap->oap->op_type != OP_NOP)) { colnr_T scol, ecol; getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol); curwin->w_cursor.coladd = ecol - scol; } else curwin->w_cursor.coladd = 0; adjust_for_sel(cap); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[" and "]" commands. * cap->arg is BACKWARD for "[" and FORWARD for "]". */ static void nv_brackets(cmdarg_T *cap) { pos_T new_pos = {0, 0, 0}; pos_T prev_pos; pos_T *pos = NULL; // init for GCC pos_T old_pos; // cursor position before command int flag; long n; int findc; int c; cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; old_pos = curwin->w_cursor; curwin->w_cursor.coladd = 0; // TODO: don't do this for an error. #ifdef FEAT_SEARCHPATH /* * "[f" or "]f" : Edit file under the cursor (same as "gf") */ if (cap->nchar == 'f') nv_gotofile(cap); else #endif #ifdef FEAT_FIND_ID /* * Find the occurrence(s) of the identifier or define under cursor * in current and included files or jump to the first occurrence. * * search list jump * fwd bwd fwd bwd fwd bwd * identifier "]i" "[i" "]I" "[I" "]^I" "[^I" * define "]d" "[d" "]D" "[D" "]^D" "[^D" */ if (vim_strchr((char_u *) # ifdef EBCDIC "iI\005dD\067", # else "iI\011dD\004", # endif cap->nchar) != NULL) { char_u *ptr; int len; if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0) clearop(cap->oap); else { find_pattern_in_path(ptr, 0, len, TRUE, cap->count0 == 0 ? !isupper(cap->nchar) : FALSE, ((cap->nchar & 0xf) == ('d' & 0xf)) ? FIND_DEFINE : FIND_ANY, cap->count1, isupper(cap->nchar) ? ACTION_SHOW_ALL : islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO, cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1, (linenr_T)MAXLNUM); curwin->w_set_curswant = TRUE; } } else #endif /* * "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')' * "[#", "]#": go to start/end of Nth innermost #if..#endif construct. * "[/", "[*", "]/", "]*": go to Nth comment start/end. * "[m" or "]m" search for prev/next start of (Java) method. * "[M" or "]M" search for prev/next end of (Java) method. */ if ( (cap->cmdchar == '[' && vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL) || (cap->cmdchar == ']' && vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL)) { if (cap->nchar == '*') cap->nchar = '/'; prev_pos.lnum = 0; if (cap->nchar == 'm' || cap->nchar == 'M') { if (cap->cmdchar == '[') findc = '{'; else findc = '}'; n = 9999; } else { findc = cap->nchar; n = cap->count1; } for ( ; n > 0; --n) { if ((pos = findmatchlimit(cap->oap, findc, (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) { if (new_pos.lnum == 0) // nothing found { if (cap->nchar != 'm' && cap->nchar != 'M') clearopbeep(cap->oap); } else pos = &new_pos; // use last one found break; } prev_pos = new_pos; curwin->w_cursor = *pos; new_pos = *pos; } curwin->w_cursor = old_pos; /* * Handle "[m", "]m", "[M" and "[M". The findmatchlimit() only * brought us to the match for "[m" and "]M" when inside a method. * Try finding the '{' or '}' we want to be at. * Also repeat for the given count. */ if (cap->nchar == 'm' || cap->nchar == 'M') { // norm is TRUE for "]M" and "[m" int norm = ((findc == '{') == (cap->nchar == 'm')); n = cap->count1; // found a match: we were inside a method if (prev_pos.lnum != 0) { pos = &prev_pos; curwin->w_cursor = prev_pos; if (norm) --n; } else pos = NULL; while (n > 0) { for (;;) { if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0) { // if not found anything, that's an error if (pos == NULL) clearopbeep(cap->oap); n = 0; break; } c = gchar_cursor(); if (c == '{' || c == '}') { // Must have found end/start of class: use it. // Or found the place to be at. if ((c == findc && norm) || (n == 1 && !norm)) { new_pos = curwin->w_cursor; pos = &new_pos; n = 0; } // if no match found at all, we started outside of the // class and we're inside now. Just go on. else if (new_pos.lnum == 0) { new_pos = curwin->w_cursor; pos = &new_pos; } // found start/end of other method: go to match else if ((pos = findmatchlimit(cap->oap, findc, (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) n = 0; else curwin->w_cursor = *pos; break; } } --n; } curwin->w_cursor = old_pos; if (pos == NULL && new_pos.lnum != 0) clearopbeep(cap->oap); } if (pos != NULL) { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = TRUE; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[[", "[]", "]]" and "][": move to start or end of function */ else if (cap->nchar == '[' || cap->nchar == ']') { if (cap->nchar == cap->cmdchar) // "]]" or "[[" flag = '{'; else flag = '}'; // "][" or "[]" curwin->w_set_curswant = TRUE; /* * Imitate strange Vi behaviour: When using "]]" with an operator * we also stop at '}'. */ if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag, (cap->oap->op_type != OP_NOP && cap->arg == FORWARD && flag == '{'))) clearopbeep(cap->oap); else { if (cap->oap->op_type == OP_NOP) beginline(BL_WHITE | BL_FIX); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "[p", "[P", "]P" and "]p": put with indent adjustment */ else if (cap->nchar == 'p' || cap->nchar == 'P') { nv_put_opt(cap, TRUE); } /* * "['", "[`", "]'" and "]`": jump to next mark */ else if (cap->nchar == '\'' || cap->nchar == '`') { pos = &curwin->w_cursor; for (n = cap->count1; n > 0; --n) { prev_pos = *pos; pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD, cap->nchar == '\''); if (pos == NULL) break; } if (pos == NULL) pos = &prev_pos; nv_cursormark(cap, cap->nchar == '\'', pos); } /* * [ or ] followed by a middle mouse click: put selected text with * indent adjustment. Any other button just does as usual. */ else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE) { (void)do_mouse(cap->oap, cap->nchar, (cap->cmdchar == ']') ? FORWARD : BACKWARD, cap->count1, PUT_FIXINDENT); } #ifdef FEAT_FOLDING /* * "[z" and "]z": move to start or end of open fold. */ else if (cap->nchar == 'z') { if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); } #endif #ifdef FEAT_DIFF /* * "[c" and "]c": move to next or previous diff-change. */ else if (cap->nchar == 'c') { if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->count1) == FAIL) clearopbeep(cap->oap); } #endif #ifdef FEAT_SPELL /* * "[s", "[S", "]s" and "]S": move to next spell error. */ else if (cap->nchar == 's' || cap->nchar == 'S') { setpcmark(); for (n = 0; n < cap->count1; ++n) if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD, cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0) { clearopbeep(cap->oap); break; } else curwin->w_set_curswant = TRUE; # ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped) foldOpenCursor(); # endif } #endif // Not a valid cap->nchar. else clearopbeep(cap->oap); } /* * Handle Normal mode "%" command. */ static void nv_percent(cmdarg_T *cap) { pos_T *pos; #if defined(FEAT_FOLDING) linenr_T lnum = curwin->w_cursor.lnum; #endif cap->oap->inclusive = TRUE; if (cap->count0) // {cnt}% : goto {cnt} percentage in file { if (cap->count0 > 100) clearopbeep(cap->oap); else { cap->oap->motion_type = MLINE; setpcmark(); // Round up, so 'normal 100%' always jumps at the line line. // Beyond 21474836 lines, (ml_line_count * 100 + 99) would // overflow on 32-bits, so use a formula with less accuracy // to avoid overflows. if (curbuf->b_ml.ml_line_count >= 21474836) curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L) / 100L * cap->count0; else curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count * cap->count0 + 99L) / 100L; if (curwin->w_cursor.lnum < 1) curwin->w_cursor.lnum = 1; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; beginline(BL_SOL | BL_FIX); } } else // "%" : go to matching paren { cap->oap->motion_type = MCHAR; cap->oap->use_reg_one = TRUE; if ((pos = findmatch(cap->oap, NUL)) == NULL) clearopbeep(cap->oap); else { setpcmark(); curwin->w_cursor = *pos; curwin->w_set_curswant = TRUE; curwin->w_cursor.coladd = 0; adjust_for_sel(cap); } } #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && lnum != curwin->w_cursor.lnum && (fdo_flags & FDO_PERCENT) && KeyTyped) foldOpenCursor(); #endif } /* * Handle "(" and ")" commands. * cap->arg is BACKWARD for "(" and FORWARD for ")". */ static void nv_brace(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->use_reg_one = TRUE; // The motion used to be inclusive for "(", but that is not what Vi does. cap->oap->inclusive = FALSE; curwin->w_set_curswant = TRUE; if (findsent(cap->arg, cap->count1) == FAIL) clearopbeep(cap->oap); else { // Don't leave the cursor on the NUL past end of line. adjust_cursor(cap->oap); curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "m" command: Mark a position. */ static void nv_mark(cmdarg_T *cap) { if (!checkclearop(cap->oap)) { if (setmark(cap->nchar) == FAIL) clearopbeep(cap->oap); } } /* * "{" and "}" commands. * cmd->arg is BACKWARD for "{" and FORWARD for "}". */ static void nv_findpar(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; cap->oap->use_reg_one = TRUE; curwin->w_set_curswant = TRUE; if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE)) clearopbeep(cap->oap); else { curwin->w_cursor.coladd = 0; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * "u" command: Undo or make lower case. */ static void nv_undo(cmdarg_T *cap) { if (cap->oap->op_type == OP_LOWER || VIsual_active) { // translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" cap->cmdchar = 'g'; cap->nchar = 'u'; nv_operator(cap); } else nv_kundo(cap); } /* * <Undo> command. */ static void nv_kundo(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf)) { clearopbeep(cap->oap); return; } #endif u_undo((int)cap->count1); curwin->w_set_curswant = TRUE; } } /* * Handle the "r" command. */ static void nv_replace(cmdarg_T *cap) { char_u *ptr; int had_ctrl_v; long n; if (checkclearop(cap->oap)) return; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(FALSE); // Don't redo a multibyte character with CTRL-V. if (cap->nchar > DEL) had_ctrl_v = NUL; } else had_ctrl_v = NUL; // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } // Visual mode "r" if (VIsual_active) { if (got_int) reset_VIsual(); if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. if (cap->nchar == CAR) cap->nchar = REPLACE_CR_NCHAR; else if (cap->nchar == NL) cap->nchar = REPLACE_NL_NCHAR; } nv_operator(cap); return; } // Break tabs, etc. if (virtual_active()) { if (u_save_cursor() == FAIL) return; if (gchar_cursor() == NUL) { // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); curwin->w_cursor.col -= cap->count1; } else if (gchar_cursor() == TAB) coladvance_force(getviscol()); } // Abort if not enough characters to replace. ptr = ml_get_cursor(); if (STRLEN(ptr) < (unsigned)cap->count1 || (has_mbyte && mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } /* * Replacing with a TAB is done by edit() when it is complicated because * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB. * Other characters are done below to avoid problems with things like * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC). */ if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) { stuffnumReadbuff(cap->count1); stuffcharReadbuff('R'); stuffcharReadbuff('\t'); stuffcharReadbuff(ESC); return; } // save line for undo if (u_save_cursor() == FAIL) return; if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* * Replace character(s) by a single newline. * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of * autoindent. The insert command depends on being on the last * character of a line or not. */ (void)del_chars(cap->count1, FALSE); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, TRUE, 'r', FALSE); } else { prep_redo(cap->oap->regname, cap->count1, NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; if (has_mbyte) { int old_State = State; if (cap->ncharC1 != 0) AppendCharToRedobuff(cap->ncharC1); if (cap->ncharC2 != 0) AppendCharToRedobuff(cap->ncharC2); // This is slow, but it handles replacing a single-byte with a // multi-byte and the other way around. Also handles adding // composing characters for utf-8. for (n = cap->count1; n > 0; --n) { State = REPLACE; if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ins_char(c); else // will be decremented further down ++curwin->w_cursor.col; } else ins_char(cap->nchar); State = old_State; if (cap->ncharC1 != 0) ins_char(cap->ncharC1); if (cap->ncharC2 != 0) ins_char(cap->ncharC2); } } else { /* * Replace the characters within one line. */ for (n = cap->count1; n > 0; --n) { /* * Get ptr again, because u_save and/or showmatch() will have * released the line. This may also happen in ins_copychar(). * At the same time we let know that the line will be changed. */ if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); if (c != NUL) ptr[curwin->w_cursor.col] = c; } else { ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); ptr[curwin->w_cursor.col] = cap->nchar; } if (p_sm && msg_silent == 0) showmatch(cap->nchar); ++curwin->w_cursor.col; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1); netbeans_removed(curbuf, curwin->w_cursor.lnum, start, (long)cap->count1); netbeans_inserted(curbuf, curwin->w_cursor.lnum, start, &ptr[start], (int)cap->count1); } #endif // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, (colnr_T)(curwin->w_cursor.col - cap->count1)); } --curwin->w_cursor.col; // cursor on the last replaced char // if the character on the left of the current cursor is a multi-byte // character, move two characters left if (has_mbyte) mb_adjust_cursor(); curbuf->b_op_end = curwin->w_cursor; curwin->w_set_curswant = TRUE; set_last_insert(cap->nchar); } } /* * 'o': Exchange start and end of Visual area. * 'O': same, but in block mode exchange left and right corners. */ static void v_swap_corners(int cmdchar) { pos_T old_cursor; colnr_T left, right; if (cmdchar == 'O' && VIsual_mode == Ctrl_V) { old_cursor = curwin->w_cursor; getvcols(curwin, &old_cursor, &VIsual, &left, &right); curwin->w_cursor.lnum = VIsual.lnum; coladvance(left); VIsual = curwin->w_cursor; curwin->w_cursor.lnum = old_cursor.lnum; curwin->w_curswant = right; // 'selection "exclusive" and cursor at right-bottom corner: move it // right one column if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e') ++curwin->w_curswant; coladvance(curwin->w_curswant); if (curwin->w_cursor.col == old_cursor.col && (!virtual_active() || curwin->w_cursor.coladd == old_cursor.coladd)) { curwin->w_cursor.lnum = VIsual.lnum; if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e') ++right; coladvance(right); VIsual = curwin->w_cursor; curwin->w_cursor.lnum = old_cursor.lnum; coladvance(left); curwin->w_curswant = left; } } else { old_cursor = curwin->w_cursor; curwin->w_cursor = VIsual; VIsual = old_cursor; curwin->w_set_curswant = TRUE; } } /* * "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE). */ static void nv_Replace(cmdarg_T *cap) { if (VIsual_active) // "R" is replace lines { cap->cmdchar = 'c'; cap->nchar = NUL; VIsual_mode_orig = VIsual_mode; // remember original area for gv VIsual_mode = 'V'; nv_operator(cap); } else if (!checkclearopq(cap->oap)) { if (!curbuf->b_p_ma) emsg(_(e_cannot_make_changes_modifiable_is_off)); else { if (virtual_active()) coladvance(getviscol()); invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE); } } } /* * "gr". */ static void nv_vreplace(cmdarg_T *cap) { if (VIsual_active) { cap->cmdchar = 'r'; cap->nchar = cap->extra_char; nv_replace(cap); // Do same as "r" in Visual mode for now } else if (!checkclearopq(cap->oap)) { if (!curbuf->b_p_ma) emsg(_(e_cannot_make_changes_modifiable_is_off)); else { if (cap->extra_char == Ctrl_V) // get another character cap->extra_char = get_literal(FALSE); stuffcharReadbuff(cap->extra_char); stuffcharReadbuff(ESC); if (virtual_active()) coladvance(getviscol()); invoke_edit(cap, TRUE, 'v', FALSE); } } } /* * Swap case for "~" command, when it does not work like an operator. */ static void n_swapchar(cmdarg_T *cap) { long n; pos_T startpos; int did_change = 0; #ifdef FEAT_NETBEANS_INTG pos_T pos; char_u *ptr; int count; #endif if (checkclearopq(cap->oap)) return; if (LINEEMPTY(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL) { clearopbeep(cap->oap); return; } prep_redo_cmd(cap); if (u_save_cursor() == FAIL) return; startpos = curwin->w_cursor; #ifdef FEAT_NETBEANS_INTG pos = startpos; #endif for (n = cap->count1; n > 0; --n) { did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor); inc_cursor(); if (gchar_cursor() == NUL) { if (vim_strchr(p_ww, '~') != NULL && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) { #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { if (did_change) { ptr = ml_get(pos.lnum); count = (int)STRLEN(ptr) - pos.col; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); } pos.col = 0; pos.lnum++; } #endif ++curwin->w_cursor.lnum; curwin->w_cursor.col = 0; if (n > 1) { if (u_savesub(curwin->w_cursor.lnum) == FAIL) break; u_clearline(); } } else break; } } #ifdef FEAT_NETBEANS_INTG if (did_change && netbeans_active()) { ptr = ml_get(pos.lnum); count = curwin->w_cursor.col - pos.col; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); } #endif check_cursor(); curwin->w_set_curswant = TRUE; if (did_change) { changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1, 0L); curbuf->b_op_start = startpos; curbuf->b_op_end = curwin->w_cursor; if (curbuf->b_op_end.col > 0) --curbuf->b_op_end.col; } } /* * Move cursor to mark. */ static void nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos) { if (check_mark(pos) == FAIL) clearop(cap->oap); else { if (cap->cmdchar == '\'' || cap->cmdchar == '`' || cap->cmdchar == '[' || cap->cmdchar == ']') setpcmark(); curwin->w_cursor = *pos; if (flag) beginline(BL_WHITE | BL_FIX); else check_cursor(); } cap->oap->motion_type = flag ? MLINE : MCHAR; if (cap->cmdchar == '`') cap->oap->use_reg_one = TRUE; cap->oap->inclusive = FALSE; // ignored if not MCHAR curwin->w_set_curswant = TRUE; } /* * Handle commands that are operators in Visual mode. */ static void v_visop(cmdarg_T *cap) { static char_u trans[] = "YyDdCcxdXdAAIIrr"; // Uppercase means linewise, except in block mode, then "D" deletes till // the end of the line, and "C" replaces till EOL if (isupper(cap->cmdchar)) { if (VIsual_mode != Ctrl_V) { VIsual_mode_orig = VIsual_mode; VIsual_mode = 'V'; } else if (cap->cmdchar == 'C' || cap->cmdchar == 'D') curwin->w_curswant = MAXCOL; } cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1); nv_operator(cap); } /* * "s" and "S" commands. */ static void nv_subst(cmdarg_T *cap) { #ifdef FEAT_TERMINAL // When showing output of term_dumpdiff() swap the top and bottom. if (term_swap_diff() == OK) return; #endif #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif if (VIsual_active) // "vs" and "vS" are the same as "vc" { if (cap->cmdchar == 'S') { VIsual_mode_orig = VIsual_mode; VIsual_mode = 'V'; } cap->cmdchar = 'c'; nv_operator(cap); } else nv_optrans(cap); } /* * Abbreviated commands. */ static void nv_abbrev(cmdarg_T *cap) { if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL) cap->cmdchar = 'x'; // DEL key behaves like 'x' // in Visual mode these commands are operators if (VIsual_active) v_visop(cap); else nv_optrans(cap); } /* * Translate a command into another command. */ static void nv_optrans(cmdarg_T *cap) { static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh", (char_u *)"d$", (char_u *)"c$", (char_u *)"cl", (char_u *)"cc", (char_u *)"yy", (char_u *)":s\r"}; static char_u *str = (char_u *)"xXDCsSY&"; if (!checkclearopq(cap->oap)) { // In Vi "2D" doesn't delete the next line. Can't translate it // either, because "2." should also not use the count. if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL) { cap->oap->start = curwin->w_cursor; cap->oap->op_type = OP_DELETE; #ifdef FEAT_EVAL set_op_var(OP_DELETE); #endif cap->count1 = 1; nv_dollar(cap); finish_op = TRUE; ResetRedobuff(); AppendCharToRedobuff('D'); } else { if (cap->count0) stuffnumReadbuff(cap->count0); stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]); } } cap->opcount = 0; } /* * "'" and "`" commands. Also for "g'" and "g`". * cap->arg is TRUE for "'" and "g'". */ static void nv_gomark(cmdarg_T *cap) { pos_T *pos; int c; #ifdef FEAT_FOLDING pos_T old_cursor = curwin->w_cursor; int old_KeyTyped = KeyTyped; // getting file may reset it #endif if (cap->cmdchar == 'g') c = cap->extra_char; else c = cap->nchar; pos = getmark(c, (cap->oap->op_type == OP_NOP)); if (pos == (pos_T *)-1) // jumped to other file { if (cap->arg) { check_cursor_lnum(); beginline(BL_WHITE | BL_FIX); } else check_cursor(); } else nv_cursormark(cap, cap->arg, pos); // May need to clear the coladd that a mark includes. if (!virtual_active()) curwin->w_cursor.coladd = 0; check_cursor_col(); #ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && pos != NULL && (pos == (pos_T *)-1 || !EQUAL_POS(old_cursor, *pos)) && (fdo_flags & FDO_MARK) && old_KeyTyped) foldOpenCursor(); #endif } /* * Handle CTRL-O, CTRL-I, "g;", "g," and "CTRL-Tab" commands. */ static void nv_pcmark(cmdarg_T *cap) { #ifdef FEAT_JUMPLIST pos_T *pos; # ifdef FEAT_FOLDING linenr_T lnum = curwin->w_cursor.lnum; int old_KeyTyped = KeyTyped; // getting file may reset it # endif if (!checkclearopq(cap->oap)) { if (cap->cmdchar == TAB && mod_mask == MOD_MASK_CTRL) { if (goto_tabpage_lastused() == FAIL) clearopbeep(cap->oap); return; } if (cap->cmdchar == 'g') pos = movechangelist((int)cap->count1); else pos = movemark((int)cap->count1); if (pos == (pos_T *)-1) // jump to other file { curwin->w_set_curswant = TRUE; check_cursor(); } else if (pos != NULL) // can jump nv_cursormark(cap, FALSE, pos); else if (cap->cmdchar == 'g') { if (curbuf->b_changelistlen == 0) emsg(_("E664: changelist is empty")); else if (cap->count1 < 0) emsg(_("E662: At start of changelist")); else emsg(_("E663: At end of changelist")); } else clearopbeep(cap->oap); # ifdef FEAT_FOLDING if (cap->oap->op_type == OP_NOP && (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum) && (fdo_flags & FDO_MARK) && old_KeyTyped) foldOpenCursor(); # endif } #else clearopbeep(cap->oap); #endif } /* * Handle '"' command. */ static void nv_regname(cmdarg_T *cap) { if (checkclearop(cap->oap)) return; #ifdef FEAT_EVAL if (cap->nchar == '=') cap->nchar = get_expr_register(); #endif if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE)) { cap->oap->regname = cap->nchar; cap->opcount = cap->count0; // remember count before '"' #ifdef FEAT_EVAL set_reg_var(cap->oap->regname); #endif } else clearopbeep(cap->oap); } /* * Handle "v", "V" and "CTRL-V" commands. * Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg * is TRUE. * Handle CTRL-Q just like CTRL-V. */ static void nv_visual(cmdarg_T *cap) { if (cap->cmdchar == Ctrl_Q) cap->cmdchar = Ctrl_V; // 'v', 'V' and CTRL-V can be used while an operator is pending to make it // characterwise, linewise, or blockwise. if (cap->oap->op_type != OP_NOP) { motion_force = cap->oap->motion_force = cap->cmdchar; finish_op = FALSE; // operator doesn't finish now but later return; } VIsual_select = cap->arg; if (VIsual_active) // change Visual mode { if (VIsual_mode == cap->cmdchar) // stop visual mode end_visual_mode(); else // toggle char/block mode { // or char/line mode VIsual_mode = cap->cmdchar; showmode(); } redraw_curbuf_later(INVERTED); // update the inversion } else // start Visual mode { check_visual_highlight(); if (cap->count0 > 0 && resel_VIsual_mode != NUL) { // use previously selected part VIsual = curwin->w_cursor; VIsual_active = TRUE; VIsual_reselect = TRUE; if (!cap->arg) // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); setmouse(); if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later /* * For V and ^V, we multiply the number of lines even if there * was only one -- webb */ if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1) { curwin->w_cursor.lnum += resel_VIsual_line_count * cap->count0 - 1; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; } VIsual_mode = resel_VIsual_mode; if (VIsual_mode == 'v') { if (resel_VIsual_line_count <= 1) { validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + resel_VIsual_vcol * cap->count0 - 1; } else curwin->w_curswant = resel_VIsual_vcol; coladvance(curwin->w_curswant); } if (resel_VIsual_vcol == MAXCOL) { curwin->w_curswant = MAXCOL; coladvance((colnr_T)MAXCOL); } else if (VIsual_mode == Ctrl_V) { validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + resel_VIsual_vcol * cap->count0 - 1; coladvance(curwin->w_curswant); } else curwin->w_set_curswant = TRUE; redraw_curbuf_later(INVERTED); // show the inversion } else { if (!cap->arg) // start Select mode when 'selectmode' contains "cmd" may_start_select('c'); n_start_visual_mode(cap->cmdchar); if (VIsual_mode != 'V' && *p_sel == 'e') ++cap->count1; // include one more char if (cap->count0 > 0 && --cap->count1 > 0) { // With a count select that many characters or lines. if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V) nv_right(cap); else if (VIsual_mode == 'V') nv_down(cap); } } } } /* * Start selection for Shift-movement keys. */ void start_selection(void) { // if 'selectmode' contains "key", start Select mode may_start_select('k'); n_start_visual_mode('v'); } /* * Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu. */ void may_start_select(int c) { VIsual_select = (stuff_empty() && typebuf_typed() && (vim_strchr(p_slm, c) != NULL)); } /* * Start Visual mode "c". * Should set VIsual_select before calling this. */ static void n_start_visual_mode(int c) { #ifdef FEAT_CONCEAL int cursor_line_was_concealed = curwin->w_p_cole > 0 && conceal_cursor_line(curwin); #endif VIsual_mode = c; VIsual_active = TRUE; VIsual_reselect = TRUE; // Corner case: the 0 position in a tab may change when going into // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting. if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB) { validate_virtcol(); coladvance(curwin->w_virtcol); } VIsual = curwin->w_cursor; #ifdef FEAT_FOLDING foldAdjustVisual(); #endif setmouse(); #ifdef FEAT_CONCEAL // Check if redraw is needed after changing the state. conceal_check_cursor_line(cursor_line_was_concealed); #endif if (p_smd && msg_silent == 0) redraw_cmdline = TRUE; // show visual mode later #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end may still be the same, and the selection needs to be owned clip_star.vmode = NUL; #endif // Only need to redraw this line, unless still need to redraw an old // Visual area (when 'lazyredraw' is set). if (curwin->w_redr_type < INVERTED) { curwin->w_old_cursor_lnum = curwin->w_cursor.lnum; curwin->w_old_visual_lnum = curwin->w_cursor.lnum; } } /* * CTRL-W: Window commands */ static void nv_window(cmdarg_T *cap) { if (cap->nchar == ':') { // "CTRL-W :" is the same as typing ":"; useful in a terminal window cap->cmdchar = ':'; cap->nchar = NUL; nv_colon(cap); } else if (!checkclearop(cap->oap)) do_window(cap->nchar, cap->count0, NUL); // everything is in window.c } /* * CTRL-Z: Suspend */ static void nv_suspend(cmdarg_T *cap) { clearop(cap->oap); if (VIsual_active) end_visual_mode(); // stop Visual mode do_cmdline_cmd((char_u *)"stop"); } /* * Commands starting with "g". */ static void nv_g_cmd(cmdarg_T *cap) { oparg_T *oap = cap->oap; pos_T tpos; int i; int flag = FALSE; switch (cap->nchar) { case Ctrl_A: case Ctrl_X: #ifdef MEM_PROFILE /* * "g^A": dump log of used memory. */ if (!VIsual_active && cap->nchar == Ctrl_A) vim_mem_profile_dump(); else #endif /* * "g^A/g^X": sequentially increment visually selected region */ if (VIsual_active) { cap->arg = TRUE; cap->cmdchar = cap->nchar; cap->nchar = NUL; nv_addsub(cap); } else clearopbeep(oap); break; /* * "gR": Enter virtual replace mode. */ case 'R': cap->arg = TRUE; nv_Replace(cap); break; case 'r': nv_vreplace(cap); break; case '&': do_cmdline_cmd((char_u *)"%s//~/&"); break; /* * "gv": Reselect the previous Visual area. If Visual already active, * exchange previous and current Visual area. */ case 'v': if (checkclearop(oap)) break; if ( curbuf->b_visual.vi_start.lnum == 0 || curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count || curbuf->b_visual.vi_end.lnum == 0) beep_flush(); else { // set w_cursor to the start of the Visual area, tpos to the end if (VIsual_active) { i = VIsual_mode; VIsual_mode = curbuf->b_visual.vi_mode; curbuf->b_visual.vi_mode = i; # ifdef FEAT_EVAL curbuf->b_visual_mode_eval = i; # endif i = curwin->w_curswant; curwin->w_curswant = curbuf->b_visual.vi_curswant; curbuf->b_visual.vi_curswant = i; tpos = curbuf->b_visual.vi_end; curbuf->b_visual.vi_end = curwin->w_cursor; curwin->w_cursor = curbuf->b_visual.vi_start; curbuf->b_visual.vi_start = VIsual; } else { VIsual_mode = curbuf->b_visual.vi_mode; curwin->w_curswant = curbuf->b_visual.vi_curswant; tpos = curbuf->b_visual.vi_end; curwin->w_cursor = curbuf->b_visual.vi_start; } VIsual_active = TRUE; VIsual_reselect = TRUE; // Set Visual to the start and w_cursor to the end of the Visual // area. Make sure they are on an existing character. check_cursor(); VIsual = curwin->w_cursor; curwin->w_cursor = tpos; check_cursor(); update_topline(); /* * When called from normal "g" command: start Select mode when * 'selectmode' contains "cmd". When called for K_SELECT, always * start Select mode. */ if (cap->arg) VIsual_select = TRUE; else may_start_select('c'); setmouse(); #ifdef FEAT_CLIPBOARD // Make sure the clipboard gets updated. Needed because start and // end are still the same, and the selection needs to be owned clip_star.vmode = NUL; #endif redraw_curbuf_later(INVERTED); showmode(); } break; /* * "gV": Don't reselect the previous Visual area after a Select mode * mapping of menu. */ case 'V': VIsual_reselect = FALSE; break; /* * "gh": start Select mode. * "gH": start Select line mode. * "g^H": start Select block mode. */ case K_BS: cap->nchar = Ctrl_H; // FALLTHROUGH case 'h': case 'H': case Ctrl_H: # ifdef EBCDIC // EBCDIC: 'v'-'h' != '^v'-'^h' if (cap->nchar == Ctrl_H) cap->cmdchar = Ctrl_V; else # endif cap->cmdchar = cap->nchar + ('v' - 'h'); cap->arg = TRUE; nv_visual(cap); break; // "gn", "gN" visually select next/previous search match // "gn" selects next match // "gN" selects previous match case 'N': case 'n': if (!current_search(cap->count1, cap->nchar == 'n')) clearopbeep(oap); break; /* * "gj" and "gk" two new funny movement keys -- up and down * movement based on *screen* line rather than *file* line. */ case 'j': case K_DOWN: // with 'nowrap' it works just like the normal "j" command. if (!curwin->w_p_wrap) { oap->motion_type = MLINE; i = cursor_down(cap->count1, oap->op_type == OP_NOP); } else i = nv_screengo(oap, FORWARD, cap->count1); if (i == FAIL) clearopbeep(oap); break; case 'k': case K_UP: // with 'nowrap' it works just like the normal "k" command. if (!curwin->w_p_wrap) { oap->motion_type = MLINE; i = cursor_up(cap->count1, oap->op_type == OP_NOP); } else i = nv_screengo(oap, BACKWARD, cap->count1); if (i == FAIL) clearopbeep(oap); break; /* * "gJ": join two lines without inserting a space. */ case 'J': nv_join(cap); break; /* * "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines. * "gm": middle of "g0" and "g$". */ case '^': flag = TRUE; // FALLTHROUGH case '0': case 'm': case K_HOME: case K_KHOME: oap->motion_type = MCHAR; oap->inclusive = FALSE; if (curwin->w_p_wrap && curwin->w_width != 0) { int width1 = curwin->w_width - curwin_col_off(); int width2 = width1 + curwin_col_off2(); validate_virtcol(); i = 0; if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0) i = (curwin->w_virtcol - width1) / width2 * width2 + width1; } else i = curwin->w_leftcol; // Go to the middle of the screen line. When 'number' or // 'relativenumber' is on and lines are wrapping the middle can be more // to the left. if (cap->nchar == 'm') i += (curwin->w_width - curwin_col_off() + ((curwin->w_p_wrap && i > 0) ? curwin_col_off2() : 0)) / 2; coladvance((colnr_T)i); if (flag) { do i = gchar_cursor(); while (VIM_ISWHITE(i) && oneright() == OK); curwin->w_valid &= ~VALID_WCOL; } curwin->w_set_curswant = TRUE; break; case 'M': { char_u *ptr = ml_get_curline(); oap->motion_type = MCHAR; oap->inclusive = FALSE; if (has_mbyte) i = mb_string2cells(ptr, (int)STRLEN(ptr)); else i = (int)STRLEN(ptr); if (cap->count0 > 0 && cap->count0 <= 100) coladvance((colnr_T)(i * cap->count0 / 100)); else coladvance((colnr_T)(i / 2)); curwin->w_set_curswant = TRUE; } break; case '_': // "g_": to the last non-blank character in the line or <count> lines // downward. cap->oap->motion_type = MCHAR; cap->oap->inclusive = TRUE; curwin->w_curswant = MAXCOL; if (cursor_down((long)(cap->count1 - 1), cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else { char_u *ptr = ml_get_curline(); // In Visual mode we may end up after the line. if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) --curwin->w_cursor.col; // Decrease the cursor column until it's on a non-blank. while (curwin->w_cursor.col > 0 && VIM_ISWHITE(ptr[curwin->w_cursor.col])) --curwin->w_cursor.col; curwin->w_set_curswant = TRUE; adjust_for_sel(cap); } break; case '$': case K_END: case K_KEND: { int col_off = curwin_col_off(); oap->motion_type = MCHAR; oap->inclusive = TRUE; if (curwin->w_p_wrap && curwin->w_width != 0) { curwin->w_curswant = MAXCOL; // so we stay at the end if (cap->count1 == 1) { int width1 = curwin->w_width - col_off; int width2 = width1 + curwin_col_off2(); validate_virtcol(); i = width1 - 1; if (curwin->w_virtcol >= (colnr_T)width1) i += ((curwin->w_virtcol - width1) / width2 + 1) * width2; coladvance((colnr_T)i); // Make sure we stick in this column. validate_virtcol(); curwin->w_curswant = curwin->w_virtcol; curwin->w_set_curswant = FALSE; if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) { /* * Check for landing on a character that got split at * the end of the line. We do not want to advance to * the next screen line. */ if (curwin->w_virtcol > (colnr_T)i) --curwin->w_cursor.col; } } else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL) clearopbeep(oap); } else { if (cap->count1 > 1) // if it fails, let the cursor still move to the last char (void)cursor_down(cap->count1 - 1, FALSE); i = curwin->w_leftcol + curwin->w_width - col_off - 1; coladvance((colnr_T)i); // if the character doesn't fit move one back if (curwin->w_cursor.col > 0 && (*mb_ptr2cells)(ml_get_cursor()) > 1) { colnr_T vcol; getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol); if (vcol >= curwin->w_leftcol + curwin->w_width - col_off) --curwin->w_cursor.col; } // Make sure we stick in this column. validate_virtcol(); curwin->w_curswant = curwin->w_virtcol; curwin->w_set_curswant = FALSE; } } break; /* * "g*" and "g#", like "*" and "#" but without using "\<" and "\>" */ case '*': case '#': #if POUND != '#' case POUND: // pound sign (sometimes equal to '#') #endif case Ctrl_RSB: // :tag or :tselect for current identifier case ']': // :tselect for current identifier nv_ident(cap); break; /* * ge and gE: go back to end of word */ case 'e': case 'E': oap->motion_type = MCHAR; curwin->w_set_curswant = TRUE; oap->inclusive = TRUE; if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL) clearopbeep(oap); break; /* * "g CTRL-G": display info about cursor position */ case Ctrl_G: cursor_pos_info(NULL); break; /* * "gi": start Insert at the last position. */ case 'i': if (curbuf->b_last_insert.lnum != 0) { curwin->w_cursor = curbuf->b_last_insert; check_cursor_lnum(); i = (int)STRLEN(ml_get_curline()); if (curwin->w_cursor.col > (colnr_T)i) { if (virtual_active()) curwin->w_cursor.coladd += curwin->w_cursor.col - i; curwin->w_cursor.col = i; } } cap->cmdchar = 'i'; nv_edit(cap); break; /* * "gI": Start insert in column 1. */ case 'I': beginline(0); if (!checkclearopq(oap)) invoke_edit(cap, FALSE, 'g', FALSE); break; #ifdef FEAT_SEARCHPATH /* * "gf": goto file, edit file under cursor * "]f" and "[f": can also be used. */ case 'f': case 'F': nv_gotofile(cap); break; #endif // "g'm" and "g`m": jump to mark without setting pcmark case '\'': cap->arg = TRUE; // FALLTHROUGH case '`': nv_gomark(cap); break; /* * "gs": Goto sleep. */ case 's': do_sleep(cap->count1 * 1000L, FALSE); break; /* * "ga": Display the ascii value of the character under the * cursor. It is displayed in decimal, hex, and octal. -- webb */ case 'a': do_ascii(NULL); break; /* * "g8": Display the bytes used for the UTF-8 character under the * cursor. It is displayed in hex. * "8g8" finds illegal byte sequence. */ case '8': if (cap->count0 == 8) utf_find_illegal(); else show_utf8(); break; // "g<": show scrollback text case '<': show_sb_text(); break; /* * "gg": Goto the first line in file. With a count it goes to * that line number like for "G". -- webb */ case 'g': cap->arg = FALSE; nv_goto(cap); break; /* * Two-character operators: * "gq" Format text * "gw" Format text and keep cursor position * "g~" Toggle the case of the text. * "gu" Change text to lower case. * "gU" Change text to upper case. * "g?" rot13 encoding * "g@" call 'operatorfunc' */ case 'q': case 'w': oap->cursor_start = curwin->w_cursor; // FALLTHROUGH case '~': case 'u': case 'U': case '?': case '@': nv_operator(cap); break; /* * "gd": Find first occurrence of pattern under the cursor in the * current function * "gD": idem, but in the current file. */ case 'd': case 'D': nv_gd(oap, cap->nchar, (int)cap->count0); break; /* * g<*Mouse> : <C-*mouse> */ case K_MIDDLEMOUSE: case K_MIDDLEDRAG: case K_MIDDLERELEASE: case K_LEFTMOUSE: case K_LEFTDRAG: case K_LEFTRELEASE: case K_MOUSEMOVE: case K_RIGHTMOUSE: case K_RIGHTDRAG: case K_RIGHTRELEASE: case K_X1MOUSE: case K_X1DRAG: case K_X1RELEASE: case K_X2MOUSE: case K_X2DRAG: case K_X2RELEASE: mod_mask = MOD_MASK_CTRL; (void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0); break; case K_IGNORE: break; /* * "gP" and "gp": same as "P" and "p" but leave cursor just after new text */ case 'p': case 'P': nv_put(cap); break; #ifdef FEAT_BYTEOFF // "go": goto byte count from start of buffer case 'o': goto_byte(cap->count0); break; #endif // "gQ": improved Ex mode case 'Q': if (text_locked()) { clearopbeep(cap->oap); text_locked_msg(); break; } if (!checkclearopq(oap)) do_exmode(TRUE); break; #ifdef FEAT_JUMPLIST case ',': nv_pcmark(cap); break; case ';': cap->count1 = -cap->count1; nv_pcmark(cap); break; #endif case 't': if (!checkclearop(oap)) goto_tabpage((int)cap->count0); break; case 'T': if (!checkclearop(oap)) goto_tabpage(-(int)cap->count1); break; case TAB: if (!checkclearop(oap) && goto_tabpage_lastused() == FAIL) clearopbeep(oap); break; case '+': case '-': // "g+" and "g-": undo or redo along the timeline if (!checkclearopq(oap)) undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1, FALSE, FALSE, FALSE); break; default: clearopbeep(oap); break; } } /* * Handle "o" and "O" commands. */ static void n_opencmd(cmdarg_T *cap) { #ifdef FEAT_CONCEAL linenr_T oldline = curwin->w_cursor.lnum; #endif if (!checkclearopq(cap->oap)) { #ifdef FEAT_FOLDING if (cap->cmdchar == 'O') // Open above the first line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL); else // Open below the last line of a folded sequence of lines (void)hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum); #endif if (u_save((linenr_T)(curwin->w_cursor.lnum - (cap->cmdchar == 'O' ? 1 : 0)), (linenr_T)(curwin->w_cursor.lnum + (cap->cmdchar == 'o' ? 1 : 0)) ) == OK && open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD, has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM : 0, 0) == OK) { #ifdef FEAT_CONCEAL if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum) redrawWinline(curwin, oldline); #endif #ifdef FEAT_SYN_HL if (curwin->w_p_cul) // force redraw of cursorline curwin->w_valid &= ~VALID_CROW; #endif // When '#' is in 'cpoptions' ignore the count. if (vim_strchr(p_cpo, CPO_HASH) != NULL) cap->count1 = 1; invoke_edit(cap, FALSE, cap->cmdchar, TRUE); } } } /* * "." command: redo last change. */ static void nv_dot(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { /* * If "restart_edit" is TRUE, the last but one command is repeated * instead of the last command (inserting text). This is used for * CTRL-O <.> in insert mode. */ if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL) clearopbeep(cap->oap); } } /* * CTRL-R: undo undo */ static void nv_redo(cmdarg_T *cap) { if (!checkclearopq(cap->oap)) { u_redo((int)cap->count1); curwin->w_set_curswant = TRUE; } } /* * Handle "U" command. */ static void nv_Undo(cmdarg_T *cap) { // In Visual mode and typing "gUU" triggers an operator if (cap->oap->op_type == OP_UPPER || VIsual_active) { // translate "gUU" to "gUgU" cap->cmdchar = 'g'; cap->nchar = 'U'; nv_operator(cap); } else if (!checkclearopq(cap->oap)) { u_undoline(); curwin->w_set_curswant = TRUE; } } /* * '~' command: If tilde is not an operator and Visual is off: swap case of a * single character. */ static void nv_tilde(cmdarg_T *cap) { if (!p_to && !VIsual_active && cap->oap->op_type != OP_TILDE) { #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif n_swapchar(cap); } else nv_operator(cap); } /* * Handle an operator command. * The actual work is done by do_pending_operator(). */ static void nv_operator(cmdarg_T *cap) { int op_type; op_type = get_op_type(cap->cmdchar, cap->nchar); #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && op_is_change(op_type) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif if (op_type == cap->oap->op_type) // double operator works on lines nv_lineop(cap); else if (!checkclearop(cap->oap)) { cap->oap->start = curwin->w_cursor; cap->oap->op_type = op_type; #ifdef FEAT_EVAL set_op_var(op_type); #endif } } #ifdef FEAT_EVAL /* * Set v:operator to the characters for "optype". */ static void set_op_var(int optype) { char_u opchars[3]; if (optype == OP_NOP) set_vim_var_string(VV_OP, NULL, 0); else { opchars[0] = get_op_char(optype); opchars[1] = get_extra_op_char(optype); opchars[2] = NUL; set_vim_var_string(VV_OP, opchars, -1); } } #endif /* * Handle linewise operator "dd", "yy", etc. * * "_" is is a strange motion command that helps make operators more logical. * It is actually implemented, but not documented in the real Vi. This motion * command actually refers to "the current line". Commands like "dd" and "yy" * are really an alternate form of "d_" and "y_". It does accept a count, so * "d3_" works to delete 3 lines. */ static void nv_lineop(cmdarg_T *cap) { cap->oap->motion_type = MLINE; if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL) clearopbeep(cap->oap); else if ( (cap->oap->op_type == OP_DELETE // only with linewise motions && cap->oap->motion_force != 'v' && cap->oap->motion_force != Ctrl_V) || cap->oap->op_type == OP_LSHIFT || cap->oap->op_type == OP_RSHIFT) beginline(BL_SOL | BL_FIX); else if (cap->oap->op_type != OP_YANK) // 'Y' does not move cursor beginline(BL_WHITE | BL_FIX); } /* * <Home> command. */ static void nv_home(cmdarg_T *cap) { // CTRL-HOME is like "gg" if (mod_mask & MOD_MASK_CTRL) nv_goto(cap); else { cap->count0 = 1; nv_pipe(cap); } ins_at_eol = FALSE; // Don't move cursor past eol (only necessary in a // one-character line). } /* * "|" command. */ static void nv_pipe(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; beginline(0); if (cap->count0 > 0) { coladvance((colnr_T)(cap->count0 - 1)); curwin->w_curswant = (colnr_T)(cap->count0 - 1); } else curwin->w_curswant = 0; // keep curswant at the column where we wanted to go, not where // we ended; differs if line is too short curwin->w_set_curswant = FALSE; } /* * Handle back-word command "b" and "B". * cap->arg is 1 for "B" */ static void nv_bck_word(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; curwin->w_set_curswant = TRUE; if (bck_word(cap->count1, cap->arg, FALSE) == FAIL) clearopbeep(cap->oap); #ifdef FEAT_FOLDING else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * Handle word motion commands "e", "E", "w" and "W". * cap->arg is TRUE for "E" and "W". */ static void nv_wordcmd(cmdarg_T *cap) { int n; int word_end; int flag = FALSE; pos_T startpos = curwin->w_cursor; /* * Set inclusive for the "E" and "e" command. */ if (cap->cmdchar == 'e' || cap->cmdchar == 'E') word_end = TRUE; else word_end = FALSE; cap->oap->inclusive = word_end; /* * "cw" and "cW" are a special case. */ if (!word_end && cap->oap->op_type == OP_CHANGE) { n = gchar_cursor(); if (n != NUL) // not an empty line { if (VIM_ISWHITE(n)) { /* * Reproduce a funny Vi behaviour: "cw" on a blank only * changes one character, not all blanks until the start of * the next word. Only do this when the 'w' flag is included * in 'cpoptions'. */ if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL) { cap->oap->inclusive = TRUE; cap->oap->motion_type = MCHAR; return; } } else { /* * This is a little strange. To match what the real Vi does, * we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided * that we are not on a space or a TAB. This seems impolite * at first, but it's really more what we mean when we say * 'cw'. * Another strangeness: When standing on the end of a word * "ce" will change until the end of the next word, but "cw" * will change only one character! This is done by setting * flag. */ cap->oap->inclusive = TRUE; word_end = TRUE; flag = TRUE; } } } cap->oap->motion_type = MCHAR; curwin->w_set_curswant = TRUE; if (word_end) n = end_word(cap->count1, cap->arg, flag, FALSE); else n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP); // Don't leave the cursor on the NUL past the end of line. Unless we // didn't move it forward. if (LT_POS(startpos, curwin->w_cursor)) adjust_cursor(cap->oap); if (n == FAIL && cap->oap->op_type == OP_NOP) clearopbeep(cap->oap); else { adjust_for_sel(cap); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } } /* * Used after a movement command: If the cursor ends up on the NUL after the * end of the line, may move it back to the last character and make the motion * inclusive. */ static void adjust_cursor(oparg_T *oap) { // The cursor cannot remain on the NUL when: // - the column is > 0 // - not in Visual mode or 'selection' is "o" // - 'virtualedit' is not "all" and not "onemore". if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL && (!VIsual_active || *p_sel == 'o') && !virtual_active() && (get_ve_flags() & VE_ONEMORE) == 0) { --curwin->w_cursor.col; // prevent cursor from moving on the trail byte if (has_mbyte) mb_adjust_cursor(); oap->inclusive = TRUE; } } /* * "0" and "^" commands. * cap->arg is the argument for beginline(). */ static void nv_beginline(cmdarg_T *cap) { cap->oap->motion_type = MCHAR; cap->oap->inclusive = FALSE; beginline(cap->arg); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif ins_at_eol = FALSE; // Don't move cursor past eol (only necessary in a // one-character line). } /* * In exclusive Visual mode, may include the last character. */ static void adjust_for_sel(cmdarg_T *cap) { if (VIsual_active && cap->oap->inclusive && *p_sel == 'e' && gchar_cursor() != NUL && LT_POS(VIsual, curwin->w_cursor)) { if (has_mbyte) inc_cursor(); else ++curwin->w_cursor.col; cap->oap->inclusive = FALSE; } } /* * Exclude last character at end of Visual area for 'selection' == "exclusive". * Should check VIsual_mode before calling this. * Returns TRUE when backed up to the previous line. */ int unadjust_for_sel(void) { pos_T *pp; if (*p_sel == 'e' && !EQUAL_POS(VIsual, curwin->w_cursor)) { if (LT_POS(VIsual, curwin->w_cursor)) pp = &curwin->w_cursor; else pp = &VIsual; if (pp->coladd > 0) --pp->coladd; else if (pp->col > 0) { --pp->col; mb_adjustpos(curbuf, pp); } else if (pp->lnum > 1) { --pp->lnum; pp->col = (colnr_T)STRLEN(ml_get(pp->lnum)); return TRUE; } } return FALSE; } /* * SELECT key in Normal or Visual mode: end of Select mode mapping. */ static void nv_select(cmdarg_T *cap) { if (VIsual_active) VIsual_select = TRUE; else if (VIsual_reselect) { cap->nchar = 'v'; // fake "gv" command cap->arg = TRUE; nv_g_cmd(cap); } } /* * "G", "gg", CTRL-END, CTRL-HOME. * cap->arg is TRUE for "G". */ static void nv_goto(cmdarg_T *cap) { linenr_T lnum; if (cap->arg) lnum = curbuf->b_ml.ml_line_count; else lnum = 1L; cap->oap->motion_type = MLINE; setpcmark(); // When a count is given, use it instead of the default lnum if (cap->count0 != 0) lnum = cap->count0; if (lnum < 1L) lnum = 1L; else if (lnum > curbuf->b_ml.ml_line_count) lnum = curbuf->b_ml.ml_line_count; curwin->w_cursor.lnum = lnum; beginline(BL_SOL | BL_FIX); #ifdef FEAT_FOLDING if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP) foldOpenCursor(); #endif } /* * CTRL-\ in Normal mode. */ static void nv_normal(cmdarg_T *cap) { if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G) { clearop(cap->oap); if (restart_edit != 0 && mode_displayed) clear_cmdline = TRUE; // unshow mode later restart_edit = 0; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) cmdwin_result = Ctrl_C; #endif if (VIsual_active) { end_visual_mode(); // stop Visual redraw_curbuf_later(INVERTED); } // CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. if (cap->nchar == Ctrl_G && p_im) restart_edit = 'a'; } else clearopbeep(cap->oap); } /* * ESC in Normal mode: beep, but don't flush buffers. * Don't even beep if we are canceling a command. */ static void nv_esc(cmdarg_T *cap) { int no_reason; no_reason = (cap->oap->op_type == OP_NOP && cap->opcount == 0 && cap->count0 == 0 && cap->oap->regname == 0 && !p_im); if (cap->arg) // TRUE for CTRL-C { if (restart_edit == 0 #ifdef FEAT_CMDWIN && cmdwin_type == 0 #endif && !VIsual_active && no_reason) { if (anyBufIsChanged()) msg(_("Type :qa! and press <Enter> to abandon all changes and exit Vim")); else msg(_("Type :qa and press <Enter> to exit Vim")); } // Don't reset "restart_edit" when 'insertmode' is set, it won't be // set again below when halfway a mapping. if (!p_im) restart_edit = 0; #ifdef FEAT_CMDWIN if (cmdwin_type != 0) { cmdwin_result = K_IGNORE; got_int = FALSE; // don't stop executing autocommands et al. return; } #endif } #ifdef FEAT_CMDWIN else if (cmdwin_type != 0 && ex_normal_busy) { // When :normal runs out of characters while in the command line window // vgetorpeek() will return ESC. Exit the cmdline window to break the // loop. cmdwin_result = K_IGNORE; return; } #endif if (VIsual_active) { end_visual_mode(); // stop Visual check_cursor_col(); // make sure cursor is not beyond EOL curwin->w_set_curswant = TRUE; redraw_curbuf_later(INVERTED); } else if (no_reason) vim_beep(BO_ESC); clearop(cap->oap); // A CTRL-C is often used at the start of a menu. When 'insertmode' is // set return to Insert mode afterwards. if (restart_edit == 0 && goto_im() && ex_normal_busy == 0) restart_edit = 'a'; } /* * Move the cursor for the "A" command. */ void set_cursor_for_append_to_line(void) { curwin->w_set_curswant = TRUE; if (get_ve_flags() == VE_ALL) { int save_State = State; // Pretend Insert mode here to allow the cursor on the // character past the end of the line State = INSERT; coladvance((colnr_T)MAXCOL); State = save_State; } else curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor()); } /* * Handle "A", "a", "I", "i" and <Insert> commands. * Also handle K_PS, start bracketed paste. */ static void nv_edit(cmdarg_T *cap) { // <Insert> is equal to "i" if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS) cap->cmdchar = 'i'; // in Visual mode "A" and "I" are an operator if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I')) { #ifdef FEAT_TERMINAL if (term_in_normal_mode()) { end_visual_mode(); clearop(cap->oap); term_enter_job_mode(); return; } #endif v_visop(cap); } // in Visual mode and after an operator "a" and "i" are for text objects else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i') && (cap->oap->op_type != OP_NOP || VIsual_active)) { #ifdef FEAT_TEXTOBJ nv_object(cap); #else clearopbeep(cap->oap); #endif } #ifdef FEAT_TERMINAL else if (term_in_normal_mode()) { clearop(cap->oap); term_enter_job_mode(); return; } #endif else if (!curbuf->b_p_ma && !p_im) { // Only give this error when 'insertmode' is off. emsg(_(e_cannot_make_changes_modifiable_is_off)); clearop(cap->oap); if (cap->cmdchar == K_PS) // drop the pasted text bracketed_paste(PASTE_INSERT, TRUE, NULL); } else if (cap->cmdchar == K_PS && VIsual_active) { pos_T old_pos = curwin->w_cursor; pos_T old_visual = VIsual; // In Visual mode the selected text is deleted. if (VIsual_mode == 'V' || curwin->w_cursor.lnum != VIsual.lnum) { shift_delete_registers(); cap->oap->regname = '1'; } else cap->oap->regname = '-'; cap->cmdchar = 'd'; cap->nchar = NUL; nv_operator(cap); do_pending_operator(cap, 0, FALSE); cap->cmdchar = K_PS; // When the last char in the line was deleted then append. Detect this // by checking if the cursor moved to before the Visual area. if (*ml_get_cursor() != NUL && LT_POS(curwin->w_cursor, old_pos) && LT_POS(curwin->w_cursor, old_visual)) inc_cursor(); // Insert to replace the deleted text with the pasted text. invoke_edit(cap, FALSE, cap->cmdchar, FALSE); } else if (!checkclearopq(cap->oap)) { switch (cap->cmdchar) { case 'A': // "A"ppend after the line set_cursor_for_append_to_line(); break; case 'I': // "I"nsert before the first non-blank if (vim_strchr(p_cpo, CPO_INSEND) == NULL) beginline(BL_WHITE); else beginline(BL_WHITE|BL_FIX); break; case K_PS: // Bracketed paste works like "a"ppend, unless the cursor is in // the first column, then it inserts. if (curwin->w_cursor.col == 0) break; // FALLTHROUGH case 'a': // "a"ppend is like "i"nsert on the next character. // increment coladd when in virtual space, increment the // column otherwise, also to append after an unprintable char if (virtual_active() && (curwin->w_cursor.coladd > 0 || *ml_get_cursor() == NUL || *ml_get_cursor() == TAB)) curwin->w_cursor.coladd++; else if (*ml_get_cursor() != NUL) inc_cursor(); break; } if (curwin->w_cursor.coladd && cap->cmdchar != 'A') { int save_State = State; // Pretend Insert mode here to allow the cursor on the // character past the end of the line State = INSERT; coladvance(getviscol()); State = save_State; } invoke_edit(cap, FALSE, cap->cmdchar, FALSE); } else if (cap->cmdchar == K_PS) // drop the pasted text bracketed_paste(PASTE_INSERT, TRUE, NULL); } /* * Invoke edit() and take care of "restart_edit" and the return value. */ static void invoke_edit( cmdarg_T *cap, int repl, // "r" or "gr" command int cmd, int startln) { int restart_edit_save = 0; // Complicated: When the user types "a<C-O>a" we don't want to do Insert // mode recursively. But when doing "a<C-O>." or "a<C-O>rx" we do allow // it. if (repl || !stuff_empty()) restart_edit_save = restart_edit; else restart_edit_save = 0; // Always reset "restart_edit", this is not a restarted edit. restart_edit = 0; if (edit(cmd, startln, cap->count1)) cap->retval |= CA_COMMAND_BUSY; if (restart_edit == 0) restart_edit = restart_edit_save; } #ifdef FEAT_TEXTOBJ /* * "a" or "i" while an operator is pending or in Visual mode: object motion. */ static void nv_object( cmdarg_T *cap) { int flag; int include; char_u *mps_save; if (cap->cmdchar == 'i') include = FALSE; // "ix" = inner object: exclude white space else include = TRUE; // "ax" = an object: include white space // Make sure (), [], {} and <> are in 'matchpairs' mps_save = curbuf->b_p_mps; curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>"; switch (cap->nchar) { case 'w': // "aw" = a word flag = current_word(cap->oap, cap->count1, include, FALSE); break; case 'W': // "aW" = a WORD flag = current_word(cap->oap, cap->count1, include, TRUE); break; case 'b': // "ab" = a braces block case '(': case ')': flag = current_block(cap->oap, cap->count1, include, '(', ')'); break; case 'B': // "aB" = a Brackets block case '{': case '}': flag = current_block(cap->oap, cap->count1, include, '{', '}'); break; case '[': // "a[" = a [] block case ']': flag = current_block(cap->oap, cap->count1, include, '[', ']'); break; case '<': // "a<" = a <> block case '>': flag = current_block(cap->oap, cap->count1, include, '<', '>'); break; case 't': // "at" = a tag block (xml and html) // Do not adjust oap->end in do_pending_operator() // otherwise there are different results for 'dit' // (note leading whitespace in last line): // 1) <b> 2) <b> // foobar foobar // </b> </b> cap->retval |= CA_NO_ADJ_OP_END; flag = current_tagblock(cap->oap, cap->count1, include); break; case 'p': // "ap" = a paragraph flag = current_par(cap->oap, cap->count1, include, 'p'); break; case 's': // "as" = a sentence flag = current_sent(cap->oap, cap->count1, include); break; case '"': // "a"" = a double quoted string case '\'': // "a'" = a single quoted string case '`': // "a`" = a backtick quoted string flag = current_quote(cap->oap, cap->count1, include, cap->nchar); break; #if 0 // TODO case 'S': // "aS" = a section case 'f': // "af" = a filename case 'u': // "au" = a URL #endif default: flag = FAIL; break; } curbuf->b_p_mps = mps_save; if (flag == FAIL) clearopbeep(cap->oap); adjust_cursor_col(); curwin->w_set_curswant = TRUE; } #endif /* * "q" command: Start/stop recording. * "q:", "q/", "q?": edit command-line in command-line window. */ static void nv_record(cmdarg_T *cap) { if (cap->oap->op_type == OP_FORMAT) { // "gqq" is the same as "gqgq": format line cap->cmdchar = 'g'; cap->nchar = 'q'; nv_operator(cap); } else if (!checkclearop(cap->oap)) { #ifdef FEAT_CMDWIN if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?') { stuffcharReadbuff(cap->nchar); stuffcharReadbuff(K_CMDWIN); } else #endif // (stop) recording into a named register, unless executing a // register if (reg_executing == 0 && do_record(cap->nchar) == FAIL) clearopbeep(cap->oap); } } /* * Handle the "@r" command. */ static void nv_at(cmdarg_T *cap) { if (checkclearop(cap->oap)) return; #ifdef FEAT_EVAL if (cap->nchar == '=') { if (get_expr_register() == NUL) return; } #endif while (cap->count1-- && !got_int) { if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL) { clearopbeep(cap->oap); break; } line_breakcheck(); } } /* * Handle the CTRL-U and CTRL-D commands. */ static void nv_halfpage(cmdarg_T *cap) { if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1) || (cap->cmdchar == Ctrl_D && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)) clearopbeep(cap->oap); else if (!checkclearop(cap->oap)) halfpage(cap->cmdchar == Ctrl_D, cap->count0); } /* * Handle "J" or "gJ" command. */ static void nv_join(cmdarg_T *cap) { if (VIsual_active) // join the visual lines nv_operator(cap); else if (!checkclearop(cap->oap)) { if (cap->count0 <= 1) cap->count0 = 2; // default for join is two lines! if (curwin->w_cursor.lnum + cap->count0 - 1 > curbuf->b_ml.ml_line_count) { // can't join when on the last line if (cap->count0 <= 2) { clearopbeep(cap->oap); return; } cap->count0 = curbuf->b_ml.ml_line_count - curwin->w_cursor.lnum + 1; } prep_redo(cap->oap->regname, cap->count0, NUL, cap->cmdchar, NUL, NUL, cap->nchar); (void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE, TRUE); } } /* * "P", "gP", "p" and "gp" commands. */ static void nv_put(cmdarg_T *cap) { nv_put_opt(cap, FALSE); } /* * "P", "gP", "p" and "gp" commands. * "fix_indent" is TRUE for "[p", "[P", "]p" and "]P". */ static void nv_put_opt(cmdarg_T *cap, int fix_indent) { int regname = 0; void *reg1 = NULL, *reg2 = NULL; int empty = FALSE; int was_visual = FALSE; int dir; int flags = 0; if (cap->oap->op_type != OP_NOP) { #ifdef FEAT_DIFF // "dp" is ":diffput" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p') { clearop(cap->oap); nv_diffgetput(TRUE, cap->opcount); } else #endif clearopbeep(cap->oap); } #ifdef FEAT_JOB_CHANNEL else if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); } #endif else { if (fix_indent) { dir = (cap->cmdchar == ']' && cap->nchar == 'p') ? FORWARD : BACKWARD; flags |= PUT_FIXINDENT; } else dir = (cap->cmdchar == 'P' || ((cap->cmdchar == 'g' || cap->cmdchar == 'z') && cap->nchar == 'P')) ? BACKWARD : FORWARD; prep_redo_cmd(cap); if (cap->cmdchar == 'g') flags |= PUT_CURSEND; else if (cap->cmdchar == 'z') flags |= PUT_BLOCK_INNER; if (VIsual_active) { // Putting in Visual mode: The put text replaces the selected // text. First delete the selected text, then put the new text. // Need to save and restore the registers that the delete // overwrites if the old contents is being put. was_visual = TRUE; regname = cap->oap->regname; #ifdef FEAT_CLIPBOARD adjust_clip_reg(&regname); #endif if (regname == 0 || regname == '"' || VIM_ISDIGIT(regname) || regname == '-' #ifdef FEAT_CLIPBOARD || (clip_unnamed && (regname == '*' || regname == '+')) #endif ) { // The delete is going to overwrite the register we want to // put, save it first. reg1 = get_register(regname, TRUE); } // Now delete the selected text. Avoid messages here. cap->cmdchar = 'd'; cap->nchar = NUL; cap->oap->regname = NUL; ++msg_silent; nv_operator(cap); do_pending_operator(cap, 0, FALSE); empty = (curbuf->b_ml.ml_flags & ML_EMPTY); --msg_silent; // delete PUT_LINE_BACKWARD; cap->oap->regname = regname; if (reg1 != NULL) { // Delete probably changed the register we want to put, save // it first. Then put back what was there before the delete. reg2 = get_register(regname, FALSE); put_register(regname, reg1); } // When deleted a linewise Visual area, put the register as // lines to avoid it joined with the next line. When deletion was // characterwise, split a line when putting lines. if (VIsual_mode == 'V') flags |= PUT_LINE; else if (VIsual_mode == 'v') flags |= PUT_LINE_SPLIT; if (VIsual_mode == Ctrl_V && dir == FORWARD) flags |= PUT_LINE_FORWARD; dir = BACKWARD; if ((VIsual_mode != 'V' && curwin->w_cursor.col < curbuf->b_op_start.col) || (VIsual_mode == 'V' && curwin->w_cursor.lnum < curbuf->b_op_start.lnum)) // cursor is at the end of the line or end of file, put // forward. dir = FORWARD; // May have been reset in do_put(). VIsual_active = TRUE; } do_put(cap->oap->regname, NULL, dir, cap->count1, flags); // If a register was saved, put it back now. if (reg2 != NULL) put_register(regname, reg2); // What to reselect with "gv"? Selecting the just put text seems to // be the most useful, since the original text was removed. if (was_visual) { curbuf->b_visual.vi_start = curbuf->b_op_start; curbuf->b_visual.vi_end = curbuf->b_op_end; // need to adjust cursor position if (*p_sel == 'e') inc(&curbuf->b_visual.vi_end); } // When all lines were selected and deleted do_put() leaves an empty // line that needs to be deleted now. if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL) { ml_delete_flags(curbuf->b_ml.ml_line_count, ML_DEL_MESSAGE); deleted_lines(curbuf->b_ml.ml_line_count + 1, 1); // If the cursor was in that line, move it to the end of the last // line. if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) { curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; coladvance((colnr_T)MAXCOL); } } auto_format(FALSE, TRUE); } } /* * "o" and "O" commands. */ static void nv_open(cmdarg_T *cap) { #ifdef FEAT_DIFF // "do" is ":diffget" if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o') { clearop(cap->oap); nv_diffgetput(FALSE, cap->opcount); } else #endif if (VIsual_active) // switch start and end of visual v_swap_corners(cap->cmdchar); #ifdef FEAT_JOB_CHANNEL else if (bt_prompt(curbuf)) clearopbeep(cap->oap); #endif else n_opencmd(cap); } #ifdef FEAT_NETBEANS_INTG static void nv_nbcmd(cmdarg_T *cap) { netbeans_keycommand(cap->nchar); } #endif #ifdef FEAT_DND static void nv_drop(cmdarg_T *cap UNUSED) { do_put('~', NULL, BACKWARD, 1L, PUT_CURSEND); } #endif /* * Trigger CursorHold event. * When waiting for a character for 'updatetime' K_CURSORHOLD is put in the * input buffer. "did_cursorhold" is set to avoid retriggering. */ static void nv_cursorhold(cmdarg_T *cap) { apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf); did_cursorhold = TRUE; cap->retval |= CA_COMMAND_BUSY; // don't call edit() now }
nv_replace(cmdarg_T *cap) { char_u *ptr; int had_ctrl_v; long n; if (checkclearop(cap->oap)) return; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(FALSE); // Don't redo a multibyte character with CTRL-V. if (cap->nchar > DEL) had_ctrl_v = NUL; } else had_ctrl_v = NUL; // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } // Visual mode "r" if (VIsual_active) { if (got_int) reset_VIsual(); if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. if (cap->nchar == CAR) cap->nchar = REPLACE_CR_NCHAR; else if (cap->nchar == NL) cap->nchar = REPLACE_NL_NCHAR; } nv_operator(cap); return; } // Break tabs, etc. if (virtual_active()) { if (u_save_cursor() == FAIL) return; if (gchar_cursor() == NUL) { // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); curwin->w_cursor.col -= cap->count1; } else if (gchar_cursor() == TAB) coladvance_force(getviscol()); } // Abort if not enough characters to replace. ptr = ml_get_cursor(); if (STRLEN(ptr) < (unsigned)cap->count1 || (has_mbyte && mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } /* * Replacing with a TAB is done by edit() when it is complicated because * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB. * Other characters are done below to avoid problems with things like * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC). */ if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) { stuffnumReadbuff(cap->count1); stuffcharReadbuff('R'); stuffcharReadbuff('\t'); stuffcharReadbuff(ESC); return; } // save line for undo if (u_save_cursor() == FAIL) return; if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* * Replace character(s) by a single newline. * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of * autoindent. The insert command depends on being on the last * character of a line or not. */ (void)del_chars(cap->count1, FALSE); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, TRUE, 'r', FALSE); } else { prep_redo(cap->oap->regname, cap->count1, NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; if (has_mbyte) { int old_State = State; if (cap->ncharC1 != 0) AppendCharToRedobuff(cap->ncharC1); if (cap->ncharC2 != 0) AppendCharToRedobuff(cap->ncharC2); // This is slow, but it handles replacing a single-byte with a // multi-byte and the other way around. Also handles adding // composing characters for utf-8. for (n = cap->count1; n > 0; --n) { State = REPLACE; if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ins_char(c); else // will be decremented further down ++curwin->w_cursor.col; } else ins_char(cap->nchar); State = old_State; if (cap->ncharC1 != 0) ins_char(cap->ncharC1); if (cap->ncharC2 != 0) ins_char(cap->ncharC2); } } else { /* * Replace the characters within one line. */ for (n = cap->count1; n > 0; --n) { /* * Get ptr again, because u_save and/or showmatch() will have * released the line. At the same time we let know that the * line will be changed. */ ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ptr[curwin->w_cursor.col] = c; } else ptr[curwin->w_cursor.col] = cap->nchar; if (p_sm && msg_silent == 0) showmatch(cap->nchar); ++curwin->w_cursor.col; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1); netbeans_removed(curbuf, curwin->w_cursor.lnum, start, (long)cap->count1); netbeans_inserted(curbuf, curwin->w_cursor.lnum, start, &ptr[start], (int)cap->count1); } #endif // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, (colnr_T)(curwin->w_cursor.col - cap->count1)); } --curwin->w_cursor.col; // cursor on the last replaced char // if the character on the left of the current cursor is a multi-byte // character, move two characters left if (has_mbyte) mb_adjust_cursor(); curbuf->b_op_end = curwin->w_cursor; curwin->w_set_curswant = TRUE; set_last_insert(cap->nchar); } }
nv_replace(cmdarg_T *cap) { char_u *ptr; int had_ctrl_v; long n; if (checkclearop(cap->oap)) return; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(FALSE); // Don't redo a multibyte character with CTRL-V. if (cap->nchar > DEL) had_ctrl_v = NUL; } else had_ctrl_v = NUL; // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } // Visual mode "r" if (VIsual_active) { if (got_int) reset_VIsual(); if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. if (cap->nchar == CAR) cap->nchar = REPLACE_CR_NCHAR; else if (cap->nchar == NL) cap->nchar = REPLACE_NL_NCHAR; } nv_operator(cap); return; } // Break tabs, etc. if (virtual_active()) { if (u_save_cursor() == FAIL) return; if (gchar_cursor() == NUL) { // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); curwin->w_cursor.col -= cap->count1; } else if (gchar_cursor() == TAB) coladvance_force(getviscol()); } // Abort if not enough characters to replace. ptr = ml_get_cursor(); if (STRLEN(ptr) < (unsigned)cap->count1 || (has_mbyte && mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } /* * Replacing with a TAB is done by edit() when it is complicated because * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB. * Other characters are done below to avoid problems with things like * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC). */ if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) { stuffnumReadbuff(cap->count1); stuffcharReadbuff('R'); stuffcharReadbuff('\t'); stuffcharReadbuff(ESC); return; } // save line for undo if (u_save_cursor() == FAIL) return; if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* * Replace character(s) by a single newline. * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of * autoindent. The insert command depends on being on the last * character of a line or not. */ (void)del_chars(cap->count1, FALSE); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, TRUE, 'r', FALSE); } else { prep_redo(cap->oap->regname, cap->count1, NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; if (has_mbyte) { int old_State = State; if (cap->ncharC1 != 0) AppendCharToRedobuff(cap->ncharC1); if (cap->ncharC2 != 0) AppendCharToRedobuff(cap->ncharC2); // This is slow, but it handles replacing a single-byte with a // multi-byte and the other way around. Also handles adding // composing characters for utf-8. for (n = cap->count1; n > 0; --n) { State = REPLACE; if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ins_char(c); else // will be decremented further down ++curwin->w_cursor.col; } else ins_char(cap->nchar); State = old_State; if (cap->ncharC1 != 0) ins_char(cap->ncharC1); if (cap->ncharC2 != 0) ins_char(cap->ncharC2); } } else { /* * Replace the characters within one line. */ for (n = cap->count1; n > 0; --n) { /* * Get ptr again, because u_save and/or showmatch() will have * released the line. This may also happen in ins_copychar(). * At the same time we let know that the line will be changed. */ if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); if (c != NUL) ptr[curwin->w_cursor.col] = c; } else { ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); ptr[curwin->w_cursor.col] = cap->nchar; } if (p_sm && msg_silent == 0) showmatch(cap->nchar); ++curwin->w_cursor.col; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1); netbeans_removed(curbuf, curwin->w_cursor.lnum, start, (long)cap->count1); netbeans_inserted(curbuf, curwin->w_cursor.lnum, start, &ptr[start], (int)cap->count1); } #endif // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, (colnr_T)(curwin->w_cursor.col - cap->count1)); } --curwin->w_cursor.col; // cursor on the last replaced char // if the character on the left of the current cursor is a multi-byte // character, move two characters left if (has_mbyte) mb_adjust_cursor(); curbuf->b_op_end = curwin->w_cursor; curwin->w_set_curswant = TRUE; set_last_insert(cap->nchar); } }
{'added': [(5102, '\t\t * released the line. This may also happen in ins_copychar().'), (5103, '\t\t * At the same time we let know that the line will be changed.'), (5109, ''), (5110, '\t\t ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);'), (5115, '\t\t{'), (5116, '\t\t ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);'), (5118, '\t\t}')], 'deleted': [(5102, '\t\t * released the line. At the same time we let know that the'), (5103, '\t\t * line will be changed.'), (5105, '\t\tptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);')]}
7
3
5,279
29,268
https://github.com/vim/vim
CVE-2021-3796
['CWE-416']
dir-item.c
btrfs_match_dir_item_name
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include "ctree.h" #include "disk-io.h" #include "hash.h" #include "transaction.h" static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len); /* * insert a name into a directory, doing overflow properly if there is a hash * collision. data_size indicates how big the item inserted should be. On * success a struct btrfs_dir_item pointer is returned, otherwise it is * an ERR_PTR. * * The name is not copied into the dir item, you have to do that yourself. */ static struct btrfs_dir_item *insert_with_overflow(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_key *cpu_key, u32 data_size, const char *name, int name_len) { int ret; char *ptr; struct btrfs_item *item; struct extent_buffer *leaf; ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size); if (ret == -EEXIST) { struct btrfs_dir_item *di; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return ERR_PTR(-EEXIST); btrfs_extend_item(root, path, data_size); } else if (ret < 0) return ERR_PTR(ret); WARN_ON(ret > 0); leaf = path->nodes[0]; item = btrfs_item_nr(path->slots[0]); ptr = btrfs_item_ptr(leaf, path->slots[0], char); BUG_ON(data_size > btrfs_item_size(leaf, item)); ptr += btrfs_item_size(leaf, item) - data_size; return (struct btrfs_dir_item *)ptr; } /* * xattrs work a lot like directories, this inserts an xattr item * into the tree */ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 objectid, const char *name, u16 name_len, const void *data, u16 data_len) { int ret = 0; struct btrfs_dir_item *dir_item; unsigned long name_ptr, data_ptr; struct btrfs_key key, location; struct btrfs_disk_key disk_key; struct extent_buffer *leaf; u32 data_size; BUG_ON(name_len + data_len > BTRFS_MAX_XATTR_SIZE(root)); key.objectid = objectid; key.type = BTRFS_XATTR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); data_size = sizeof(*dir_item) + name_len + data_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) return PTR_ERR(dir_item); memset(&location, 0, sizeof(location)); leaf = path->nodes[0]; btrfs_cpu_key_to_disk(&disk_key, &location); btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); btrfs_set_dir_data_len(leaf, dir_item, data_len); name_ptr = (unsigned long)(dir_item + 1); data_ptr = (unsigned long)((char *)name_ptr + name_len); write_extent_buffer(leaf, name, name_ptr, name_len); write_extent_buffer(leaf, data, data_ptr, data_len); btrfs_mark_buffer_dirty(path->nodes[0]); return ret; } /* * insert a directory item in the tree, doing all the magic for * both indexes. 'dir' indicates which objectid to insert it into, * 'location' is the key to stuff into the directory item, 'type' is the * type of the inode we're pointing to, and 'index' is the sequence number * to use for the second index (if one is created). * Will return 0 or -ENOMEM */ int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, const char *name, int name_len, struct inode *dir, struct btrfs_key *location, u8 type, u64 index) { int ret = 0; int ret2 = 0; struct btrfs_path *path; struct btrfs_dir_item *dir_item; struct extent_buffer *leaf; unsigned long name_ptr; struct btrfs_key key; struct btrfs_disk_key disk_key; u32 data_size; key.objectid = btrfs_ino(dir); key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; btrfs_cpu_key_to_disk(&disk_key, location); data_size = sizeof(*dir_item) + name_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) { ret = PTR_ERR(dir_item); if (ret == -EEXIST) goto second_insert; goto out_free; } leaf = path->nodes[0]; btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, type); btrfs_set_dir_data_len(leaf, dir_item, 0); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); name_ptr = (unsigned long)(dir_item + 1); write_extent_buffer(leaf, name, name_ptr, name_len); btrfs_mark_buffer_dirty(leaf); second_insert: /* FIXME, use some real flag for selecting the extra index */ if (root == root->fs_info->tree_root) { ret = 0; goto out_free; } btrfs_release_path(path); ret2 = btrfs_insert_delayed_dir_index(trans, root, name, name_len, dir, &disk_key, type, index); out_free: btrfs_free_path(path); if (ret) return ret; if (ret2) return ret2; return 0; } /* * lookup a directory item based on name. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) */ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir, const char *name, int name_len) { int ret; struct btrfs_key key; struct btrfs_dir_item *di; int data_size; struct extent_buffer *leaf; int slot; struct btrfs_path *path; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = dir; key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); /* return back any errors */ if (ret < 0) goto out; /* nothing found, we're safe */ if (ret > 0) { ret = 0; goto out; } /* we found an item, look for our name in the item */ di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) { /* our exact name was found */ ret = -EEXIST; goto out; } /* * see if there is room in the item to insert this * name */ data_size = sizeof(*di) + name_len; leaf = path->nodes[0]; slot = path->slots[0]; if (data_size + btrfs_item_size_nr(leaf, slot) + sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root)) { ret = -EOVERFLOW; } else { /* plenty of insertion room */ ret = 0; } out: btrfs_free_path(path); return ret; } /* * lookup a directory item based on index. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) * * The name is used to make sure the index really points to the name you were * looking for. */ struct btrfs_dir_item * btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, u64 objectid, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_DIR_INDEX_KEY; key.offset = objectid; ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return ERR_PTR(-ENOENT); return btrfs_match_dir_item_name(root, path, name, name_len); } struct btrfs_dir_item * btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path, u64 dirid, const char *name, int name_len) { struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u32 nritems; int ret; key.objectid = dirid; key.type = BTRFS_DIR_INDEX_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) return ERR_PTR(ret); leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); while (1) { if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(root, path); if (ret < 0) return ERR_PTR(ret); if (ret > 0) break; leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); continue; } btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY) break; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return di; path->slots[0]++; } return NULL; } struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, u16 name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_XATTR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } /* * helper function to look at the directory item pointed to by 'path' * this walks through all the entries in a dir item and finds one * for a specific name. */ static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; } /* * given a pointer into a directory item, delete it. This * handles items that have more than one entry in them. */ int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_dir_item *di) { struct extent_buffer *leaf; u32 sub_item_len; u32 item_len; int ret = 0; leaf = path->nodes[0]; sub_item_len = sizeof(*di) + btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di); item_len = btrfs_item_size_nr(leaf, path->slots[0]); if (sub_item_len == item_len) { ret = btrfs_del_item(trans, root, path); } else { /* MARKER */ unsigned long ptr = (unsigned long)di; unsigned long start; start = btrfs_item_ptr_offset(leaf, path->slots[0]); memmove_extent_buffer(leaf, ptr, ptr + sub_item_len, item_len - (ptr + sub_item_len - start)); btrfs_truncate_item(root, path, item_len - sub_item_len, 1); } return ret; } int verify_dir_item(struct btrfs_root *root, struct extent_buffer *leaf, struct btrfs_dir_item *dir_item) { u16 namelen = BTRFS_NAME_LEN; u8 type = btrfs_dir_type(leaf, dir_item); if (type >= BTRFS_FT_MAX) { btrfs_crit(root->fs_info, "invalid dir item type: %d", (int)type); return 1; } if (type == BTRFS_FT_XATTR) namelen = XATTR_NAME_MAX; if (btrfs_dir_name_len(leaf, dir_item) > namelen) { btrfs_crit(root->fs_info, "invalid dir item name len: %u", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } /* BTRFS_MAX_XATTR_SIZE is the same for all dir items */ if ((btrfs_dir_data_len(leaf, dir_item) + btrfs_dir_name_len(leaf, dir_item)) > BTRFS_MAX_XATTR_SIZE(root)) { btrfs_crit(root->fs_info, "invalid dir item name + data len: %u + %u", (unsigned)btrfs_dir_name_len(leaf, dir_item), (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } return 0; }
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include "ctree.h" #include "disk-io.h" #include "hash.h" #include "transaction.h" /* * insert a name into a directory, doing overflow properly if there is a hash * collision. data_size indicates how big the item inserted should be. On * success a struct btrfs_dir_item pointer is returned, otherwise it is * an ERR_PTR. * * The name is not copied into the dir item, you have to do that yourself. */ static struct btrfs_dir_item *insert_with_overflow(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_key *cpu_key, u32 data_size, const char *name, int name_len) { int ret; char *ptr; struct btrfs_item *item; struct extent_buffer *leaf; ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size); if (ret == -EEXIST) { struct btrfs_dir_item *di; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return ERR_PTR(-EEXIST); btrfs_extend_item(root, path, data_size); } else if (ret < 0) return ERR_PTR(ret); WARN_ON(ret > 0); leaf = path->nodes[0]; item = btrfs_item_nr(path->slots[0]); ptr = btrfs_item_ptr(leaf, path->slots[0], char); BUG_ON(data_size > btrfs_item_size(leaf, item)); ptr += btrfs_item_size(leaf, item) - data_size; return (struct btrfs_dir_item *)ptr; } /* * xattrs work a lot like directories, this inserts an xattr item * into the tree */ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 objectid, const char *name, u16 name_len, const void *data, u16 data_len) { int ret = 0; struct btrfs_dir_item *dir_item; unsigned long name_ptr, data_ptr; struct btrfs_key key, location; struct btrfs_disk_key disk_key; struct extent_buffer *leaf; u32 data_size; BUG_ON(name_len + data_len > BTRFS_MAX_XATTR_SIZE(root)); key.objectid = objectid; key.type = BTRFS_XATTR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); data_size = sizeof(*dir_item) + name_len + data_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) return PTR_ERR(dir_item); memset(&location, 0, sizeof(location)); leaf = path->nodes[0]; btrfs_cpu_key_to_disk(&disk_key, &location); btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); btrfs_set_dir_data_len(leaf, dir_item, data_len); name_ptr = (unsigned long)(dir_item + 1); data_ptr = (unsigned long)((char *)name_ptr + name_len); write_extent_buffer(leaf, name, name_ptr, name_len); write_extent_buffer(leaf, data, data_ptr, data_len); btrfs_mark_buffer_dirty(path->nodes[0]); return ret; } /* * insert a directory item in the tree, doing all the magic for * both indexes. 'dir' indicates which objectid to insert it into, * 'location' is the key to stuff into the directory item, 'type' is the * type of the inode we're pointing to, and 'index' is the sequence number * to use for the second index (if one is created). * Will return 0 or -ENOMEM */ int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, const char *name, int name_len, struct inode *dir, struct btrfs_key *location, u8 type, u64 index) { int ret = 0; int ret2 = 0; struct btrfs_path *path; struct btrfs_dir_item *dir_item; struct extent_buffer *leaf; unsigned long name_ptr; struct btrfs_key key; struct btrfs_disk_key disk_key; u32 data_size; key.objectid = btrfs_ino(dir); key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; btrfs_cpu_key_to_disk(&disk_key, location); data_size = sizeof(*dir_item) + name_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) { ret = PTR_ERR(dir_item); if (ret == -EEXIST) goto second_insert; goto out_free; } leaf = path->nodes[0]; btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, type); btrfs_set_dir_data_len(leaf, dir_item, 0); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); name_ptr = (unsigned long)(dir_item + 1); write_extent_buffer(leaf, name, name_ptr, name_len); btrfs_mark_buffer_dirty(leaf); second_insert: /* FIXME, use some real flag for selecting the extra index */ if (root == root->fs_info->tree_root) { ret = 0; goto out_free; } btrfs_release_path(path); ret2 = btrfs_insert_delayed_dir_index(trans, root, name, name_len, dir, &disk_key, type, index); out_free: btrfs_free_path(path); if (ret) return ret; if (ret2) return ret2; return 0; } /* * lookup a directory item based on name. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) */ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir, const char *name, int name_len) { int ret; struct btrfs_key key; struct btrfs_dir_item *di; int data_size; struct extent_buffer *leaf; int slot; struct btrfs_path *path; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = dir; key.type = BTRFS_DIR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); /* return back any errors */ if (ret < 0) goto out; /* nothing found, we're safe */ if (ret > 0) { ret = 0; goto out; } /* we found an item, look for our name in the item */ di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) { /* our exact name was found */ ret = -EEXIST; goto out; } /* * see if there is room in the item to insert this * name */ data_size = sizeof(*di) + name_len; leaf = path->nodes[0]; slot = path->slots[0]; if (data_size + btrfs_item_size_nr(leaf, slot) + sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root)) { ret = -EOVERFLOW; } else { /* plenty of insertion room */ ret = 0; } out: btrfs_free_path(path); return ret; } /* * lookup a directory item based on index. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) * * The name is used to make sure the index really points to the name you were * looking for. */ struct btrfs_dir_item * btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, u64 objectid, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_DIR_INDEX_KEY; key.offset = objectid; ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return ERR_PTR(-ENOENT); return btrfs_match_dir_item_name(root, path, name, name_len); } struct btrfs_dir_item * btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path, u64 dirid, const char *name, int name_len) { struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u32 nritems; int ret; key.objectid = dirid; key.type = BTRFS_DIR_INDEX_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) return ERR_PTR(ret); leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); while (1) { if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(root, path); if (ret < 0) return ERR_PTR(ret); if (ret > 0) break; leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); continue; } btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY) break; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return di; path->slots[0]++; } return NULL; } struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, u16 name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_XATTR_ITEM_KEY; key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } /* * helper function to look at the directory item pointed to by 'path' * this walks through all the entries in a dir item and finds one * for a specific name. */ struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; } /* * given a pointer into a directory item, delete it. This * handles items that have more than one entry in them. */ int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_dir_item *di) { struct extent_buffer *leaf; u32 sub_item_len; u32 item_len; int ret = 0; leaf = path->nodes[0]; sub_item_len = sizeof(*di) + btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di); item_len = btrfs_item_size_nr(leaf, path->slots[0]); if (sub_item_len == item_len) { ret = btrfs_del_item(trans, root, path); } else { /* MARKER */ unsigned long ptr = (unsigned long)di; unsigned long start; start = btrfs_item_ptr_offset(leaf, path->slots[0]); memmove_extent_buffer(leaf, ptr, ptr + sub_item_len, item_len - (ptr + sub_item_len - start)); btrfs_truncate_item(root, path, item_len - sub_item_len, 1); } return ret; } int verify_dir_item(struct btrfs_root *root, struct extent_buffer *leaf, struct btrfs_dir_item *dir_item) { u16 namelen = BTRFS_NAME_LEN; u8 type = btrfs_dir_type(leaf, dir_item); if (type >= BTRFS_FT_MAX) { btrfs_crit(root->fs_info, "invalid dir item type: %d", (int)type); return 1; } if (type == BTRFS_FT_XATTR) namelen = XATTR_NAME_MAX; if (btrfs_dir_name_len(leaf, dir_item) > namelen) { btrfs_crit(root->fs_info, "invalid dir item name len: %u", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } /* BTRFS_MAX_XATTR_SIZE is the same for all dir items */ if ((btrfs_dir_data_len(leaf, dir_item) + btrfs_dir_name_len(leaf, dir_item)) > BTRFS_MAX_XATTR_SIZE(root)) { btrfs_crit(root->fs_info, "invalid dir item name + data len: %u + %u", (unsigned)btrfs_dir_name_len(leaf, dir_item), (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } return 0; }
static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; }
struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; }
{'added': [(382, 'struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,'), (383, '\t\t\t\t\t\t struct btrfs_path *path,'), (384, '\t\t\t\t\t\t const char *name, int name_len)')], 'deleted': [(24, 'static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,'), (25, '\t\t\t struct btrfs_path *path,'), (26, '\t\t\t const char *name, int name_len);'), (27, ''), (386, 'static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,'), (387, '\t\t\t struct btrfs_path *path,'), (388, '\t\t\t const char *name, int name_len)')]}
3
7
349
2,274
https://github.com/torvalds/linux
CVE-2014-9710
['CWE-362']
rxe_mr.c
mem_check_range
/* * Copyright (c) 2016 Mellanox Technologies Ltd. All rights reserved. * Copyright (c) 2015 System Fabric Works, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "rxe.h" #include "rxe_loc.h" /* * lfsr (linear feedback shift register) with period 255 */ static u8 rxe_get_key(void) { static u32 key = 1; key = key << 1; key |= (0 != (key & 0x100)) ^ (0 != (key & 0x10)) ^ (0 != (key & 0x80)) ^ (0 != (key & 0x40)); key &= 0xff; return key; } int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } } #define IB_ACCESS_REMOTE (IB_ACCESS_REMOTE_READ \ | IB_ACCESS_REMOTE_WRITE \ | IB_ACCESS_REMOTE_ATOMIC) static void rxe_mem_init(int access, struct rxe_mem *mem) { u32 lkey = mem->pelem.index << 8 | rxe_get_key(); u32 rkey = (access & IB_ACCESS_REMOTE) ? lkey : 0; if (mem->pelem.pool->type == RXE_TYPE_MR) { mem->ibmr.lkey = lkey; mem->ibmr.rkey = rkey; } mem->lkey = lkey; mem->rkey = rkey; mem->state = RXE_MEM_STATE_INVALID; mem->type = RXE_MEM_TYPE_NONE; mem->map_shift = ilog2(RXE_BUF_PER_MAP); } void rxe_mem_cleanup(void *arg) { struct rxe_mem *mem = arg; int i; if (mem->umem) ib_umem_release(mem->umem); if (mem->map) { for (i = 0; i < mem->num_map; i++) kfree(mem->map[i]); kfree(mem->map); } } static int rxe_mem_alloc(struct rxe_dev *rxe, struct rxe_mem *mem, int num_buf) { int i; int num_map; struct rxe_map **map = mem->map; num_map = (num_buf + RXE_BUF_PER_MAP - 1) / RXE_BUF_PER_MAP; mem->map = kmalloc_array(num_map, sizeof(*map), GFP_KERNEL); if (!mem->map) goto err1; for (i = 0; i < num_map; i++) { mem->map[i] = kmalloc(sizeof(**map), GFP_KERNEL); if (!mem->map[i]) goto err2; } WARN_ON(!is_power_of_2(RXE_BUF_PER_MAP)); mem->map_shift = ilog2(RXE_BUF_PER_MAP); mem->map_mask = RXE_BUF_PER_MAP - 1; mem->num_buf = num_buf; mem->num_map = num_map; mem->max_buf = num_map * RXE_BUF_PER_MAP; return 0; err2: for (i--; i >= 0; i--) kfree(mem->map[i]); kfree(mem->map); err1: return -ENOMEM; } int rxe_mem_init_dma(struct rxe_dev *rxe, struct rxe_pd *pd, int access, struct rxe_mem *mem) { rxe_mem_init(access, mem); mem->pd = pd; mem->access = access; mem->state = RXE_MEM_STATE_VALID; mem->type = RXE_MEM_TYPE_DMA; return 0; } int rxe_mem_init_user(struct rxe_dev *rxe, struct rxe_pd *pd, u64 start, u64 length, u64 iova, int access, struct ib_udata *udata, struct rxe_mem *mem) { int entry; struct rxe_map **map; struct rxe_phys_buf *buf = NULL; struct ib_umem *umem; struct scatterlist *sg; int num_buf; void *vaddr; int err; umem = ib_umem_get(pd->ibpd.uobject->context, start, length, access, 0); if (IS_ERR(umem)) { pr_warn("err %d from rxe_umem_get\n", (int)PTR_ERR(umem)); err = -EINVAL; goto err1; } mem->umem = umem; num_buf = umem->nmap; rxe_mem_init(access, mem); err = rxe_mem_alloc(rxe, mem, num_buf); if (err) { pr_warn("err %d from rxe_mem_alloc\n", err); ib_umem_release(umem); goto err1; } WARN_ON(!is_power_of_2(umem->page_size)); mem->page_shift = ilog2(umem->page_size); mem->page_mask = umem->page_size - 1; num_buf = 0; map = mem->map; if (length > 0) { buf = map[0]->buf; for_each_sg(umem->sg_head.sgl, sg, umem->nmap, entry) { vaddr = page_address(sg_page(sg)); if (!vaddr) { pr_warn("null vaddr\n"); err = -ENOMEM; goto err1; } buf->addr = (uintptr_t)vaddr; buf->size = umem->page_size; num_buf++; buf++; if (num_buf >= RXE_BUF_PER_MAP) { map++; buf = map[0]->buf; num_buf = 0; } } } mem->pd = pd; mem->umem = umem; mem->access = access; mem->length = length; mem->iova = iova; mem->va = start; mem->offset = ib_umem_offset(umem); mem->state = RXE_MEM_STATE_VALID; mem->type = RXE_MEM_TYPE_MR; return 0; err1: return err; } int rxe_mem_init_fast(struct rxe_dev *rxe, struct rxe_pd *pd, int max_pages, struct rxe_mem *mem) { int err; rxe_mem_init(0, mem); /* In fastreg, we also set the rkey */ mem->ibmr.rkey = mem->ibmr.lkey; err = rxe_mem_alloc(rxe, mem, max_pages); if (err) goto err1; mem->pd = pd; mem->max_buf = max_pages; mem->state = RXE_MEM_STATE_FREE; mem->type = RXE_MEM_TYPE_MR; return 0; err1: return err; } static void lookup_iova( struct rxe_mem *mem, u64 iova, int *m_out, int *n_out, size_t *offset_out) { size_t offset = iova - mem->iova + mem->offset; int map_index; int buf_index; u64 length; if (likely(mem->page_shift)) { *offset_out = offset & mem->page_mask; offset >>= mem->page_shift; *n_out = offset & mem->map_mask; *m_out = offset >> mem->map_shift; } else { map_index = 0; buf_index = 0; length = mem->map[map_index]->buf[buf_index].size; while (offset >= length) { offset -= length; buf_index++; if (buf_index == RXE_BUF_PER_MAP) { map_index++; buf_index = 0; } length = mem->map[map_index]->buf[buf_index].size; } *m_out = map_index; *n_out = buf_index; *offset_out = offset; } } void *iova_to_vaddr(struct rxe_mem *mem, u64 iova, int length) { size_t offset; int m, n; void *addr; if (mem->state != RXE_MEM_STATE_VALID) { pr_warn("mem not in valid state\n"); addr = NULL; goto out; } if (!mem->map) { addr = (void *)(uintptr_t)iova; goto out; } if (mem_check_range(mem, iova, length)) { pr_warn("range violation\n"); addr = NULL; goto out; } lookup_iova(mem, iova, &m, &n, &offset); if (offset + length > mem->map[m]->buf[n].size) { pr_warn("crosses page boundary\n"); addr = NULL; goto out; } addr = (void *)(uintptr_t)mem->map[m]->buf[n].addr + offset; out: return addr; } /* copy data from a range (vaddr, vaddr+length-1) to or from * a mem object starting at iova. Compute incremental value of * crc32 if crcp is not zero. caller must hold a reference to mem */ int rxe_mem_copy(struct rxe_mem *mem, u64 iova, void *addr, int length, enum copy_direction dir, u32 *crcp) { int err; int bytes; u8 *va; struct rxe_map **map; struct rxe_phys_buf *buf; int m; int i; size_t offset; u32 crc = crcp ? (*crcp) : 0; if (length == 0) return 0; if (mem->type == RXE_MEM_TYPE_DMA) { u8 *src, *dest; src = (dir == to_mem_obj) ? addr : ((void *)(uintptr_t)iova); dest = (dir == to_mem_obj) ? ((void *)(uintptr_t)iova) : addr; if (crcp) *crcp = crc32_le(*crcp, src, length); memcpy(dest, src, length); return 0; } WARN_ON(!mem->map); err = mem_check_range(mem, iova, length); if (err) { err = -EFAULT; goto err1; } lookup_iova(mem, iova, &m, &i, &offset); map = mem->map + m; buf = map[0]->buf + i; while (length > 0) { u8 *src, *dest; va = (u8 *)(uintptr_t)buf->addr + offset; src = (dir == to_mem_obj) ? addr : va; dest = (dir == to_mem_obj) ? va : addr; bytes = buf->size - offset; if (bytes > length) bytes = length; if (crcp) crc = crc32_le(crc, src, bytes); memcpy(dest, src, bytes); length -= bytes; addr += bytes; offset = 0; buf++; i++; if (i == RXE_BUF_PER_MAP) { i = 0; map++; buf = map[0]->buf; } } if (crcp) *crcp = crc; return 0; err1: return err; } /* copy data in or out of a wqe, i.e. sg list * under the control of a dma descriptor */ int copy_data( struct rxe_dev *rxe, struct rxe_pd *pd, int access, struct rxe_dma_info *dma, void *addr, int length, enum copy_direction dir, u32 *crcp) { int bytes; struct rxe_sge *sge = &dma->sge[dma->cur_sge]; int offset = dma->sge_offset; int resid = dma->resid; struct rxe_mem *mem = NULL; u64 iova; int err; if (length == 0) return 0; if (length > resid) { err = -EINVAL; goto err2; } if (sge->length && (offset < sge->length)) { mem = lookup_mem(pd, access, sge->lkey, lookup_local); if (!mem) { err = -EINVAL; goto err1; } } while (length > 0) { bytes = length; if (offset >= sge->length) { if (mem) { rxe_drop_ref(mem); mem = NULL; } sge++; dma->cur_sge++; offset = 0; if (dma->cur_sge >= dma->num_sge) { err = -ENOSPC; goto err2; } if (sge->length) { mem = lookup_mem(pd, access, sge->lkey, lookup_local); if (!mem) { err = -EINVAL; goto err1; } } else { continue; } } if (bytes > sge->length - offset) bytes = sge->length - offset; if (bytes > 0) { iova = sge->addr + offset; err = rxe_mem_copy(mem, iova, addr, bytes, dir, crcp); if (err) goto err2; offset += bytes; resid -= bytes; length -= bytes; addr += bytes; } } dma->sge_offset = offset; dma->resid = resid; if (mem) rxe_drop_ref(mem); return 0; err2: if (mem) rxe_drop_ref(mem); err1: return err; } int advance_dma_data(struct rxe_dma_info *dma, unsigned int length) { struct rxe_sge *sge = &dma->sge[dma->cur_sge]; int offset = dma->sge_offset; int resid = dma->resid; while (length) { unsigned int bytes; if (offset >= sge->length) { sge++; dma->cur_sge++; offset = 0; if (dma->cur_sge >= dma->num_sge) return -ENOSPC; } bytes = length; if (bytes > sge->length - offset) bytes = sge->length - offset; offset += bytes; resid -= bytes; length -= bytes; } dma->sge_offset = offset; dma->resid = resid; return 0; } /* (1) find the mem (mr or mw) corresponding to lkey/rkey * depending on lookup_type * (2) verify that the (qp) pd matches the mem pd * (3) verify that the mem can support the requested access * (4) verify that mem state is valid */ struct rxe_mem *lookup_mem(struct rxe_pd *pd, int access, u32 key, enum lookup_type type) { struct rxe_mem *mem; struct rxe_dev *rxe = to_rdev(pd->ibpd.device); int index = key >> 8; if (index >= RXE_MIN_MR_INDEX && index <= RXE_MAX_MR_INDEX) { mem = rxe_pool_get_index(&rxe->mr_pool, index); if (!mem) goto err1; } else { goto err1; } if ((type == lookup_local && mem->lkey != key) || (type == lookup_remote && mem->rkey != key)) goto err2; if (mem->pd != pd) goto err2; if (access && !(access & mem->access)) goto err2; if (mem->state != RXE_MEM_STATE_VALID) goto err2; return mem; err2: rxe_drop_ref(mem); err1: return NULL; } int rxe_mem_map_pages(struct rxe_dev *rxe, struct rxe_mem *mem, u64 *page, int num_pages, u64 iova) { int i; int num_buf; int err; struct rxe_map **map; struct rxe_phys_buf *buf; int page_size; if (num_pages > mem->max_buf) { err = -EINVAL; goto err1; } num_buf = 0; page_size = 1 << mem->page_shift; map = mem->map; buf = map[0]->buf; for (i = 0; i < num_pages; i++) { buf->addr = *page++; buf->size = page_size; buf++; num_buf++; if (num_buf == RXE_BUF_PER_MAP) { map++; buf = map[0]->buf; num_buf = 0; } } mem->iova = iova; mem->va = iova; mem->length = num_pages << mem->page_shift; mem->state = RXE_MEM_STATE_VALID; return 0; err1: return err; }
/* * Copyright (c) 2016 Mellanox Technologies Ltd. All rights reserved. * Copyright (c) 2015 System Fabric Works, Inc. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "rxe.h" #include "rxe_loc.h" /* * lfsr (linear feedback shift register) with period 255 */ static u8 rxe_get_key(void) { static u32 key = 1; key = key << 1; key |= (0 != (key & 0x100)) ^ (0 != (key & 0x10)) ^ (0 != (key & 0x80)) ^ (0 != (key & 0x40)); key &= 0xff; return key; } int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } } #define IB_ACCESS_REMOTE (IB_ACCESS_REMOTE_READ \ | IB_ACCESS_REMOTE_WRITE \ | IB_ACCESS_REMOTE_ATOMIC) static void rxe_mem_init(int access, struct rxe_mem *mem) { u32 lkey = mem->pelem.index << 8 | rxe_get_key(); u32 rkey = (access & IB_ACCESS_REMOTE) ? lkey : 0; if (mem->pelem.pool->type == RXE_TYPE_MR) { mem->ibmr.lkey = lkey; mem->ibmr.rkey = rkey; } mem->lkey = lkey; mem->rkey = rkey; mem->state = RXE_MEM_STATE_INVALID; mem->type = RXE_MEM_TYPE_NONE; mem->map_shift = ilog2(RXE_BUF_PER_MAP); } void rxe_mem_cleanup(void *arg) { struct rxe_mem *mem = arg; int i; if (mem->umem) ib_umem_release(mem->umem); if (mem->map) { for (i = 0; i < mem->num_map; i++) kfree(mem->map[i]); kfree(mem->map); } } static int rxe_mem_alloc(struct rxe_dev *rxe, struct rxe_mem *mem, int num_buf) { int i; int num_map; struct rxe_map **map = mem->map; num_map = (num_buf + RXE_BUF_PER_MAP - 1) / RXE_BUF_PER_MAP; mem->map = kmalloc_array(num_map, sizeof(*map), GFP_KERNEL); if (!mem->map) goto err1; for (i = 0; i < num_map; i++) { mem->map[i] = kmalloc(sizeof(**map), GFP_KERNEL); if (!mem->map[i]) goto err2; } WARN_ON(!is_power_of_2(RXE_BUF_PER_MAP)); mem->map_shift = ilog2(RXE_BUF_PER_MAP); mem->map_mask = RXE_BUF_PER_MAP - 1; mem->num_buf = num_buf; mem->num_map = num_map; mem->max_buf = num_map * RXE_BUF_PER_MAP; return 0; err2: for (i--; i >= 0; i--) kfree(mem->map[i]); kfree(mem->map); err1: return -ENOMEM; } int rxe_mem_init_dma(struct rxe_dev *rxe, struct rxe_pd *pd, int access, struct rxe_mem *mem) { rxe_mem_init(access, mem); mem->pd = pd; mem->access = access; mem->state = RXE_MEM_STATE_VALID; mem->type = RXE_MEM_TYPE_DMA; return 0; } int rxe_mem_init_user(struct rxe_dev *rxe, struct rxe_pd *pd, u64 start, u64 length, u64 iova, int access, struct ib_udata *udata, struct rxe_mem *mem) { int entry; struct rxe_map **map; struct rxe_phys_buf *buf = NULL; struct ib_umem *umem; struct scatterlist *sg; int num_buf; void *vaddr; int err; umem = ib_umem_get(pd->ibpd.uobject->context, start, length, access, 0); if (IS_ERR(umem)) { pr_warn("err %d from rxe_umem_get\n", (int)PTR_ERR(umem)); err = -EINVAL; goto err1; } mem->umem = umem; num_buf = umem->nmap; rxe_mem_init(access, mem); err = rxe_mem_alloc(rxe, mem, num_buf); if (err) { pr_warn("err %d from rxe_mem_alloc\n", err); ib_umem_release(umem); goto err1; } WARN_ON(!is_power_of_2(umem->page_size)); mem->page_shift = ilog2(umem->page_size); mem->page_mask = umem->page_size - 1; num_buf = 0; map = mem->map; if (length > 0) { buf = map[0]->buf; for_each_sg(umem->sg_head.sgl, sg, umem->nmap, entry) { vaddr = page_address(sg_page(sg)); if (!vaddr) { pr_warn("null vaddr\n"); err = -ENOMEM; goto err1; } buf->addr = (uintptr_t)vaddr; buf->size = umem->page_size; num_buf++; buf++; if (num_buf >= RXE_BUF_PER_MAP) { map++; buf = map[0]->buf; num_buf = 0; } } } mem->pd = pd; mem->umem = umem; mem->access = access; mem->length = length; mem->iova = iova; mem->va = start; mem->offset = ib_umem_offset(umem); mem->state = RXE_MEM_STATE_VALID; mem->type = RXE_MEM_TYPE_MR; return 0; err1: return err; } int rxe_mem_init_fast(struct rxe_dev *rxe, struct rxe_pd *pd, int max_pages, struct rxe_mem *mem) { int err; rxe_mem_init(0, mem); /* In fastreg, we also set the rkey */ mem->ibmr.rkey = mem->ibmr.lkey; err = rxe_mem_alloc(rxe, mem, max_pages); if (err) goto err1; mem->pd = pd; mem->max_buf = max_pages; mem->state = RXE_MEM_STATE_FREE; mem->type = RXE_MEM_TYPE_MR; return 0; err1: return err; } static void lookup_iova( struct rxe_mem *mem, u64 iova, int *m_out, int *n_out, size_t *offset_out) { size_t offset = iova - mem->iova + mem->offset; int map_index; int buf_index; u64 length; if (likely(mem->page_shift)) { *offset_out = offset & mem->page_mask; offset >>= mem->page_shift; *n_out = offset & mem->map_mask; *m_out = offset >> mem->map_shift; } else { map_index = 0; buf_index = 0; length = mem->map[map_index]->buf[buf_index].size; while (offset >= length) { offset -= length; buf_index++; if (buf_index == RXE_BUF_PER_MAP) { map_index++; buf_index = 0; } length = mem->map[map_index]->buf[buf_index].size; } *m_out = map_index; *n_out = buf_index; *offset_out = offset; } } void *iova_to_vaddr(struct rxe_mem *mem, u64 iova, int length) { size_t offset; int m, n; void *addr; if (mem->state != RXE_MEM_STATE_VALID) { pr_warn("mem not in valid state\n"); addr = NULL; goto out; } if (!mem->map) { addr = (void *)(uintptr_t)iova; goto out; } if (mem_check_range(mem, iova, length)) { pr_warn("range violation\n"); addr = NULL; goto out; } lookup_iova(mem, iova, &m, &n, &offset); if (offset + length > mem->map[m]->buf[n].size) { pr_warn("crosses page boundary\n"); addr = NULL; goto out; } addr = (void *)(uintptr_t)mem->map[m]->buf[n].addr + offset; out: return addr; } /* copy data from a range (vaddr, vaddr+length-1) to or from * a mem object starting at iova. Compute incremental value of * crc32 if crcp is not zero. caller must hold a reference to mem */ int rxe_mem_copy(struct rxe_mem *mem, u64 iova, void *addr, int length, enum copy_direction dir, u32 *crcp) { int err; int bytes; u8 *va; struct rxe_map **map; struct rxe_phys_buf *buf; int m; int i; size_t offset; u32 crc = crcp ? (*crcp) : 0; if (length == 0) return 0; if (mem->type == RXE_MEM_TYPE_DMA) { u8 *src, *dest; src = (dir == to_mem_obj) ? addr : ((void *)(uintptr_t)iova); dest = (dir == to_mem_obj) ? ((void *)(uintptr_t)iova) : addr; if (crcp) *crcp = crc32_le(*crcp, src, length); memcpy(dest, src, length); return 0; } WARN_ON(!mem->map); err = mem_check_range(mem, iova, length); if (err) { err = -EFAULT; goto err1; } lookup_iova(mem, iova, &m, &i, &offset); map = mem->map + m; buf = map[0]->buf + i; while (length > 0) { u8 *src, *dest; va = (u8 *)(uintptr_t)buf->addr + offset; src = (dir == to_mem_obj) ? addr : va; dest = (dir == to_mem_obj) ? va : addr; bytes = buf->size - offset; if (bytes > length) bytes = length; if (crcp) crc = crc32_le(crc, src, bytes); memcpy(dest, src, bytes); length -= bytes; addr += bytes; offset = 0; buf++; i++; if (i == RXE_BUF_PER_MAP) { i = 0; map++; buf = map[0]->buf; } } if (crcp) *crcp = crc; return 0; err1: return err; } /* copy data in or out of a wqe, i.e. sg list * under the control of a dma descriptor */ int copy_data( struct rxe_dev *rxe, struct rxe_pd *pd, int access, struct rxe_dma_info *dma, void *addr, int length, enum copy_direction dir, u32 *crcp) { int bytes; struct rxe_sge *sge = &dma->sge[dma->cur_sge]; int offset = dma->sge_offset; int resid = dma->resid; struct rxe_mem *mem = NULL; u64 iova; int err; if (length == 0) return 0; if (length > resid) { err = -EINVAL; goto err2; } if (sge->length && (offset < sge->length)) { mem = lookup_mem(pd, access, sge->lkey, lookup_local); if (!mem) { err = -EINVAL; goto err1; } } while (length > 0) { bytes = length; if (offset >= sge->length) { if (mem) { rxe_drop_ref(mem); mem = NULL; } sge++; dma->cur_sge++; offset = 0; if (dma->cur_sge >= dma->num_sge) { err = -ENOSPC; goto err2; } if (sge->length) { mem = lookup_mem(pd, access, sge->lkey, lookup_local); if (!mem) { err = -EINVAL; goto err1; } } else { continue; } } if (bytes > sge->length - offset) bytes = sge->length - offset; if (bytes > 0) { iova = sge->addr + offset; err = rxe_mem_copy(mem, iova, addr, bytes, dir, crcp); if (err) goto err2; offset += bytes; resid -= bytes; length -= bytes; addr += bytes; } } dma->sge_offset = offset; dma->resid = resid; if (mem) rxe_drop_ref(mem); return 0; err2: if (mem) rxe_drop_ref(mem); err1: return err; } int advance_dma_data(struct rxe_dma_info *dma, unsigned int length) { struct rxe_sge *sge = &dma->sge[dma->cur_sge]; int offset = dma->sge_offset; int resid = dma->resid; while (length) { unsigned int bytes; if (offset >= sge->length) { sge++; dma->cur_sge++; offset = 0; if (dma->cur_sge >= dma->num_sge) return -ENOSPC; } bytes = length; if (bytes > sge->length - offset) bytes = sge->length - offset; offset += bytes; resid -= bytes; length -= bytes; } dma->sge_offset = offset; dma->resid = resid; return 0; } /* (1) find the mem (mr or mw) corresponding to lkey/rkey * depending on lookup_type * (2) verify that the (qp) pd matches the mem pd * (3) verify that the mem can support the requested access * (4) verify that mem state is valid */ struct rxe_mem *lookup_mem(struct rxe_pd *pd, int access, u32 key, enum lookup_type type) { struct rxe_mem *mem; struct rxe_dev *rxe = to_rdev(pd->ibpd.device); int index = key >> 8; if (index >= RXE_MIN_MR_INDEX && index <= RXE_MAX_MR_INDEX) { mem = rxe_pool_get_index(&rxe->mr_pool, index); if (!mem) goto err1; } else { goto err1; } if ((type == lookup_local && mem->lkey != key) || (type == lookup_remote && mem->rkey != key)) goto err2; if (mem->pd != pd) goto err2; if (access && !(access & mem->access)) goto err2; if (mem->state != RXE_MEM_STATE_VALID) goto err2; return mem; err2: rxe_drop_ref(mem); err1: return NULL; } int rxe_mem_map_pages(struct rxe_dev *rxe, struct rxe_mem *mem, u64 *page, int num_pages, u64 iova) { int i; int num_buf; int err; struct rxe_map **map; struct rxe_phys_buf *buf; int page_size; if (num_pages > mem->max_buf) { err = -EINVAL; goto err1; } num_buf = 0; page_size = 1 << mem->page_shift; map = mem->map; buf = map[0]->buf; for (i = 0; i < num_pages; i++) { buf->addr = *page++; buf->size = page_size; buf++; num_buf++; if (num_buf == RXE_BUF_PER_MAP) { map++; buf = map[0]->buf; num_buf = 0; } } mem->iova = iova; mem->va = iova; mem->length = num_pages << mem->page_shift; mem->state = RXE_MEM_STATE_VALID; return 0; err1: return err; }
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } }
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }
{'added': [(62, '\t\tif (iova < mem->iova ||'), (63, '\t\t length > mem->length ||'), (64, '\t\t iova > mem->iova + mem->length - length)'), (65, '\t\t\treturn -EFAULT;'), (66, '\t\treturn 0;')], 'deleted': [(62, '\t\treturn ((iova < mem->iova) ||'), (63, '\t\t\t((iova + length) > (mem->iova + mem->length))) ?'), (64, '\t\t\t-EFAULT : 0;')]}
5
3
467
2,702
https://github.com/torvalds/linux
CVE-2016-8636
['CWE-190']
llcp_core.c
nfc_llcp_build_gb
/* * Copyright (C) 2011 Intel Corporation. All rights reserved. * Copyright (C) 2014 Marvell International Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #define pr_fmt(fmt) "llcp: %s: " fmt, __func__ #include <linux/init.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/nfc.h> #include "nfc.h" #include "llcp.h" static u8 llcp_magic[3] = {0x46, 0x66, 0x6d}; static LIST_HEAD(llcp_devices); static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb); void nfc_llcp_sock_link(struct llcp_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } void nfc_llcp_sock_unlink(struct llcp_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } void nfc_llcp_socket_remote_param_init(struct nfc_llcp_sock *sock) { sock->remote_rw = LLCP_DEFAULT_RW; sock->remote_miu = LLCP_MAX_MIU + 1; } static void nfc_llcp_socket_purge(struct nfc_llcp_sock *sock) { struct nfc_llcp_local *local = sock->local; struct sk_buff *s, *tmp; pr_debug("%p\n", &sock->sk); skb_queue_purge(&sock->tx_queue); skb_queue_purge(&sock->tx_pending_queue); if (local == NULL) return; /* Search for local pending SKBs that are related to this socket */ skb_queue_walk_safe(&local->tx_queue, s, tmp) { if (s->sk != &sock->sk) continue; skb_unlink(s, &local->tx_queue); kfree_skb(s); } } static void nfc_llcp_socket_release(struct nfc_llcp_local *local, bool device, int err) { struct sock *sk; struct hlist_node *tmp; struct nfc_llcp_sock *llcp_sock; skb_queue_purge(&local->tx_queue); write_lock(&local->sockets.lock); sk_for_each_safe(sk, tmp, &local->sockets.head) { llcp_sock = nfc_llcp_sock(sk); bh_lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (sk->sk_state == LLCP_CONNECTED) nfc_put_device(llcp_sock->dev); if (sk->sk_state == LLCP_LISTEN) { struct nfc_llcp_sock *lsk, *n; struct sock *accept_sk; list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue, accept_queue) { accept_sk = &lsk->sk; bh_lock_sock(accept_sk); nfc_llcp_accept_unlink(accept_sk); if (err) accept_sk->sk_err = err; accept_sk->sk_state = LLCP_CLOSED; accept_sk->sk_state_change(sk); bh_unlock_sock(accept_sk); } } if (err) sk->sk_err = err; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); bh_unlock_sock(sk); sk_del_node_init(sk); } write_unlock(&local->sockets.lock); /* If we still have a device, we keep the RAW sockets alive */ if (device == true) return; write_lock(&local->raw_sockets.lock); sk_for_each_safe(sk, tmp, &local->raw_sockets.head) { llcp_sock = nfc_llcp_sock(sk); bh_lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (err) sk->sk_err = err; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); bh_unlock_sock(sk); sk_del_node_init(sk); } write_unlock(&local->raw_sockets.lock); } struct nfc_llcp_local *nfc_llcp_local_get(struct nfc_llcp_local *local) { kref_get(&local->ref); return local; } static void local_cleanup(struct nfc_llcp_local *local) { nfc_llcp_socket_release(local, false, ENXIO); del_timer_sync(&local->link_timer); skb_queue_purge(&local->tx_queue); cancel_work_sync(&local->tx_work); cancel_work_sync(&local->rx_work); cancel_work_sync(&local->timeout_work); kfree_skb(local->rx_pending); del_timer_sync(&local->sdreq_timer); cancel_work_sync(&local->sdreq_timeout_work); nfc_llcp_free_sdp_tlv_list(&local->pending_sdreqs); } static void local_release(struct kref *ref) { struct nfc_llcp_local *local; local = container_of(ref, struct nfc_llcp_local, ref); list_del(&local->list); local_cleanup(local); kfree(local); } int nfc_llcp_local_put(struct nfc_llcp_local *local) { if (local == NULL) return 0; return kref_put(&local->ref, local_release); } static struct nfc_llcp_sock *nfc_llcp_sock_get(struct nfc_llcp_local *local, u8 ssap, u8 dsap) { struct sock *sk; struct nfc_llcp_sock *llcp_sock, *tmp_sock; pr_debug("ssap dsap %d %d\n", ssap, dsap); if (ssap == 0 && dsap == 0) return NULL; read_lock(&local->sockets.lock); llcp_sock = NULL; sk_for_each(sk, &local->sockets.head) { tmp_sock = nfc_llcp_sock(sk); if (tmp_sock->ssap == ssap && tmp_sock->dsap == dsap) { llcp_sock = tmp_sock; break; } } read_unlock(&local->sockets.lock); if (llcp_sock == NULL) return NULL; sock_hold(&llcp_sock->sk); return llcp_sock; } static void nfc_llcp_sock_put(struct nfc_llcp_sock *sock) { sock_put(&sock->sk); } static void nfc_llcp_timeout_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, timeout_work); nfc_dep_link_down(local->dev); } static void nfc_llcp_symm_timer(struct timer_list *t) { struct nfc_llcp_local *local = from_timer(local, t, link_timer); pr_err("SYMM timeout\n"); schedule_work(&local->timeout_work); } static void nfc_llcp_sdreq_timeout_work(struct work_struct *work) { unsigned long time; HLIST_HEAD(nl_sdres_list); struct hlist_node *n; struct nfc_llcp_sdp_tlv *sdp; struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, sdreq_timeout_work); mutex_lock(&local->sdreq_lock); time = jiffies - msecs_to_jiffies(3 * local->remote_lto); hlist_for_each_entry_safe(sdp, n, &local->pending_sdreqs, node) { if (time_after(sdp->time, time)) continue; sdp->sap = LLCP_SDP_UNBOUND; hlist_del(&sdp->node); hlist_add_head(&sdp->node, &nl_sdres_list); } if (!hlist_empty(&local->pending_sdreqs)) mod_timer(&local->sdreq_timer, jiffies + msecs_to_jiffies(3 * local->remote_lto)); mutex_unlock(&local->sdreq_lock); if (!hlist_empty(&nl_sdres_list)) nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list); } static void nfc_llcp_sdreq_timer(struct timer_list *t) { struct nfc_llcp_local *local = from_timer(local, t, sdreq_timer); schedule_work(&local->sdreq_timeout_work); } struct nfc_llcp_local *nfc_llcp_find_local(struct nfc_dev *dev) { struct nfc_llcp_local *local; list_for_each_entry(local, &llcp_devices, list) if (local->dev == dev) return local; pr_debug("No device found\n"); return NULL; } static char *wks[] = { NULL, NULL, /* SDP */ "urn:nfc:sn:ip", "urn:nfc:sn:obex", "urn:nfc:sn:snep", }; static int nfc_llcp_wks_sap(char *service_name, size_t service_name_len) { int sap, num_wks; pr_debug("%s\n", service_name); if (service_name == NULL) return -EINVAL; num_wks = ARRAY_SIZE(wks); for (sap = 0; sap < num_wks; sap++) { if (wks[sap] == NULL) continue; if (strncmp(wks[sap], service_name, service_name_len) == 0) return sap; } return -EINVAL; } static struct nfc_llcp_sock *nfc_llcp_sock_from_sn(struct nfc_llcp_local *local, u8 *sn, size_t sn_len) { struct sock *sk; struct nfc_llcp_sock *llcp_sock, *tmp_sock; pr_debug("sn %zd %p\n", sn_len, sn); if (sn == NULL || sn_len == 0) return NULL; read_lock(&local->sockets.lock); llcp_sock = NULL; sk_for_each(sk, &local->sockets.head) { tmp_sock = nfc_llcp_sock(sk); pr_debug("llcp sock %p\n", tmp_sock); if (tmp_sock->sk.sk_type == SOCK_STREAM && tmp_sock->sk.sk_state != LLCP_LISTEN) continue; if (tmp_sock->sk.sk_type == SOCK_DGRAM && tmp_sock->sk.sk_state != LLCP_BOUND) continue; if (tmp_sock->service_name == NULL || tmp_sock->service_name_len == 0) continue; if (tmp_sock->service_name_len != sn_len) continue; if (memcmp(sn, tmp_sock->service_name, sn_len) == 0) { llcp_sock = tmp_sock; break; } } read_unlock(&local->sockets.lock); pr_debug("Found llcp sock %p\n", llcp_sock); return llcp_sock; } u8 nfc_llcp_get_sdp_ssap(struct nfc_llcp_local *local, struct nfc_llcp_sock *sock) { mutex_lock(&local->sdp_lock); if (sock->service_name != NULL && sock->service_name_len > 0) { int ssap = nfc_llcp_wks_sap(sock->service_name, sock->service_name_len); if (ssap > 0) { pr_debug("WKS %d\n", ssap); /* This is a WKS, let's check if it's free */ if (local->local_wks & BIT(ssap)) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } set_bit(ssap, &local->local_wks); mutex_unlock(&local->sdp_lock); return ssap; } /* * Check if there already is a non WKS socket bound * to this service name. */ if (nfc_llcp_sock_from_sn(local, sock->service_name, sock->service_name_len) != NULL) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } mutex_unlock(&local->sdp_lock); return LLCP_SDP_UNBOUND; } else if (sock->ssap != 0 && sock->ssap < LLCP_WKS_NUM_SAP) { if (!test_bit(sock->ssap, &local->local_wks)) { set_bit(sock->ssap, &local->local_wks); mutex_unlock(&local->sdp_lock); return sock->ssap; } } mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } u8 nfc_llcp_get_local_ssap(struct nfc_llcp_local *local) { u8 local_ssap; mutex_lock(&local->sdp_lock); local_ssap = find_first_zero_bit(&local->local_sap, LLCP_LOCAL_NUM_SAP); if (local_ssap == LLCP_LOCAL_NUM_SAP) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } set_bit(local_ssap, &local->local_sap); mutex_unlock(&local->sdp_lock); return local_ssap + LLCP_LOCAL_SAP_OFFSET; } void nfc_llcp_put_ssap(struct nfc_llcp_local *local, u8 ssap) { u8 local_ssap; unsigned long *sdp; if (ssap < LLCP_WKS_NUM_SAP) { local_ssap = ssap; sdp = &local->local_wks; } else if (ssap < LLCP_LOCAL_NUM_SAP) { atomic_t *client_cnt; local_ssap = ssap - LLCP_WKS_NUM_SAP; sdp = &local->local_sdp; client_cnt = &local->local_sdp_cnt[local_ssap]; pr_debug("%d clients\n", atomic_read(client_cnt)); mutex_lock(&local->sdp_lock); if (atomic_dec_and_test(client_cnt)) { struct nfc_llcp_sock *l_sock; pr_debug("No more clients for SAP %d\n", ssap); clear_bit(local_ssap, sdp); /* Find the listening sock and set it back to UNBOUND */ l_sock = nfc_llcp_sock_get(local, ssap, LLCP_SAP_SDP); if (l_sock) { l_sock->ssap = LLCP_SDP_UNBOUND; nfc_llcp_sock_put(l_sock); } } mutex_unlock(&local->sdp_lock); return; } else if (ssap < LLCP_MAX_SAP) { local_ssap = ssap - LLCP_LOCAL_NUM_SAP; sdp = &local->local_sap; } else { return; } mutex_lock(&local->sdp_lock); clear_bit(local_ssap, sdp); mutex_unlock(&local->sdp_lock); } static u8 nfc_llcp_reserve_sdp_ssap(struct nfc_llcp_local *local) { u8 ssap; mutex_lock(&local->sdp_lock); ssap = find_first_zero_bit(&local->local_sdp, LLCP_SDP_NUM_SAP); if (ssap == LLCP_SDP_NUM_SAP) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } pr_debug("SDP ssap %d\n", LLCP_WKS_NUM_SAP + ssap); set_bit(ssap, &local->local_sdp); mutex_unlock(&local->sdp_lock); return LLCP_WKS_NUM_SAP + ssap; } static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, *version_tlv, version, version_length; u8 *lto_tlv, lto_length; u8 *wks_tlv, wks_length; u8 *miux_tlv, miux_length; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; } u8 *nfc_llcp_general_bytes(struct nfc_dev *dev, size_t *general_bytes_len) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) { *general_bytes_len = 0; return NULL; } nfc_llcp_build_gb(local); *general_bytes_len = local->gb_len; return local->gb; } int nfc_llcp_set_remote_gb(struct nfc_dev *dev, u8 *gb, u8 gb_len) { struct nfc_llcp_local *local; if (gb_len < 3 || gb_len > NFC_MAX_GT_LEN) return -EINVAL; local = nfc_llcp_find_local(dev); if (local == NULL) { pr_err("No LLCP device\n"); return -ENODEV; } memset(local->remote_gb, 0, NFC_MAX_GT_LEN); memcpy(local->remote_gb, gb, gb_len); local->remote_gb_len = gb_len; if (memcmp(local->remote_gb, llcp_magic, 3)) { pr_err("MAC does not support LLCP\n"); return -EINVAL; } return nfc_llcp_parse_gb_tlv(local, &local->remote_gb[3], local->remote_gb_len - 3); } static u8 nfc_llcp_dsap(struct sk_buff *pdu) { return (pdu->data[0] & 0xfc) >> 2; } static u8 nfc_llcp_ptype(struct sk_buff *pdu) { return ((pdu->data[0] & 0x03) << 2) | ((pdu->data[1] & 0xc0) >> 6); } static u8 nfc_llcp_ssap(struct sk_buff *pdu) { return pdu->data[1] & 0x3f; } static u8 nfc_llcp_ns(struct sk_buff *pdu) { return pdu->data[2] >> 4; } static u8 nfc_llcp_nr(struct sk_buff *pdu) { return pdu->data[2] & 0xf; } static void nfc_llcp_set_nrns(struct nfc_llcp_sock *sock, struct sk_buff *pdu) { pdu->data[2] = (sock->send_n << 4) | (sock->recv_n); sock->send_n = (sock->send_n + 1) % 16; sock->recv_ack_n = (sock->recv_n - 1) % 16; } void nfc_llcp_send_to_raw_sock(struct nfc_llcp_local *local, struct sk_buff *skb, u8 direction) { struct sk_buff *skb_copy = NULL, *nskb; struct sock *sk; u8 *data; read_lock(&local->raw_sockets.lock); sk_for_each(sk, &local->raw_sockets.head) { if (sk->sk_state != LLCP_BOUND) continue; if (skb_copy == NULL) { skb_copy = __pskb_copy_fclone(skb, NFC_RAW_HEADER_SIZE, GFP_ATOMIC, true); if (skb_copy == NULL) continue; data = skb_push(skb_copy, NFC_RAW_HEADER_SIZE); data[0] = local->dev ? local->dev->idx : 0xFF; data[1] = direction & 0x01; data[1] |= (RAW_PAYLOAD_LLCP << 1); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&local->raw_sockets.lock); kfree_skb(skb_copy); } static void nfc_llcp_tx_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, tx_work); struct sk_buff *skb; struct sock *sk; struct nfc_llcp_sock *llcp_sock; skb = skb_dequeue(&local->tx_queue); if (skb != NULL) { sk = skb->sk; llcp_sock = nfc_llcp_sock(sk); if (llcp_sock == NULL && nfc_llcp_ptype(skb) == LLCP_PDU_I) { kfree_skb(skb); nfc_llcp_send_symm(local->dev); } else if (llcp_sock && !llcp_sock->remote_ready) { skb_queue_head(&local->tx_queue, skb); nfc_llcp_send_symm(local->dev); } else { struct sk_buff *copy_skb = NULL; u8 ptype = nfc_llcp_ptype(skb); int ret; pr_debug("Sending pending skb\n"); print_hex_dump_debug("LLCP Tx: ", DUMP_PREFIX_OFFSET, 16, 1, skb->data, skb->len, true); if (ptype == LLCP_PDU_DISC && sk != NULL && sk->sk_state == LLCP_DISCONNECTING) { nfc_llcp_sock_unlink(&local->sockets, sk); sock_orphan(sk); sock_put(sk); } if (ptype == LLCP_PDU_I) copy_skb = skb_copy(skb, GFP_ATOMIC); __net_timestamp(skb); nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_TX); ret = nfc_data_exchange(local->dev, local->target_idx, skb, nfc_llcp_recv, local); if (ret) { kfree_skb(copy_skb); goto out; } if (ptype == LLCP_PDU_I && copy_skb) skb_queue_tail(&llcp_sock->tx_pending_queue, copy_skb); } } else { nfc_llcp_send_symm(local->dev); } out: mod_timer(&local->link_timer, jiffies + msecs_to_jiffies(2 * local->remote_lto)); } static struct nfc_llcp_sock *nfc_llcp_connecting_sock_get(struct nfc_llcp_local *local, u8 ssap) { struct sock *sk; struct nfc_llcp_sock *llcp_sock; read_lock(&local->connecting_sockets.lock); sk_for_each(sk, &local->connecting_sockets.head) { llcp_sock = nfc_llcp_sock(sk); if (llcp_sock->ssap == ssap) { sock_hold(&llcp_sock->sk); goto out; } } llcp_sock = NULL; out: read_unlock(&local->connecting_sockets.lock); return llcp_sock; } static struct nfc_llcp_sock *nfc_llcp_sock_get_sn(struct nfc_llcp_local *local, u8 *sn, size_t sn_len) { struct nfc_llcp_sock *llcp_sock; llcp_sock = nfc_llcp_sock_from_sn(local, sn, sn_len); if (llcp_sock == NULL) return NULL; sock_hold(&llcp_sock->sk); return llcp_sock; } static u8 *nfc_llcp_connect_sn(struct sk_buff *skb, size_t *sn_len) { u8 *tlv = &skb->data[2], type, length; size_t tlv_array_len = skb->len - LLCP_HEADER_SIZE, offset = 0; while (offset < tlv_array_len) { type = tlv[0]; length = tlv[1]; pr_debug("type 0x%x length %d\n", type, length); if (type == LLCP_TLV_SN) { *sn_len = length; return &tlv[2]; } offset += length + 2; tlv += length + 2; } return NULL; } static void nfc_llcp_recv_ui(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct nfc_llcp_ui_cb *ui_cb; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); ui_cb = nfc_llcp_ui_skb_cb(skb); ui_cb->dsap = dsap; ui_cb->ssap = ssap; pr_debug("%d %d\n", dsap, ssap); /* We're looking for a bound socket, not a client one */ llcp_sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP); if (llcp_sock == NULL || llcp_sock->sk.sk_type != SOCK_DGRAM) return; /* There is no sequence with UI frames */ skb_pull(skb, LLCP_HEADER_SIZE); if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) { /* * UI frames will be freed from the socket layer, so we * need to keep them alive until someone receives them. */ skb_get(skb); } else { pr_err("Receive queue is full\n"); } nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_connect(struct nfc_llcp_local *local, struct sk_buff *skb) { struct sock *new_sk, *parent; struct nfc_llcp_sock *sock, *new_sock; u8 dsap, ssap, reason; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("%d %d\n", dsap, ssap); if (dsap != LLCP_SAP_SDP) { sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP); if (sock == NULL || sock->sk.sk_state != LLCP_LISTEN) { reason = LLCP_DM_NOBOUND; goto fail; } } else { u8 *sn; size_t sn_len; sn = nfc_llcp_connect_sn(skb, &sn_len); if (sn == NULL) { reason = LLCP_DM_NOBOUND; goto fail; } pr_debug("Service name length %zu\n", sn_len); sock = nfc_llcp_sock_get_sn(local, sn, sn_len); if (sock == NULL) { reason = LLCP_DM_NOBOUND; goto fail; } } lock_sock(&sock->sk); parent = &sock->sk; if (sk_acceptq_is_full(parent)) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } if (sock->ssap == LLCP_SDP_UNBOUND) { u8 ssap = nfc_llcp_reserve_sdp_ssap(local); pr_debug("First client, reserving %d\n", ssap); if (ssap == LLCP_SAP_MAX) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } sock->ssap = ssap; } new_sk = nfc_llcp_sock_alloc(NULL, parent->sk_type, GFP_ATOMIC, 0); if (new_sk == NULL) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } new_sock = nfc_llcp_sock(new_sk); new_sock->dev = local->dev; new_sock->local = nfc_llcp_local_get(local); new_sock->rw = sock->rw; new_sock->miux = sock->miux; new_sock->nfc_protocol = sock->nfc_protocol; new_sock->dsap = ssap; new_sock->target_idx = local->target_idx; new_sock->parent = parent; new_sock->ssap = sock->ssap; if (sock->ssap < LLCP_LOCAL_NUM_SAP && sock->ssap >= LLCP_WKS_NUM_SAP) { atomic_t *client_count; pr_debug("reserved_ssap %d for %p\n", sock->ssap, new_sock); client_count = &local->local_sdp_cnt[sock->ssap - LLCP_WKS_NUM_SAP]; atomic_inc(client_count); new_sock->reserved_ssap = sock->ssap; } nfc_llcp_parse_connection_tlv(new_sock, &skb->data[LLCP_HEADER_SIZE], skb->len - LLCP_HEADER_SIZE); pr_debug("new sock %p sk %p\n", new_sock, &new_sock->sk); nfc_llcp_sock_link(&local->sockets, new_sk); nfc_llcp_accept_enqueue(&sock->sk, new_sk); nfc_get_device(local->dev->idx); new_sk->sk_state = LLCP_CONNECTED; /* Wake the listening processes */ parent->sk_data_ready(parent); /* Send CC */ nfc_llcp_send_cc(new_sock); release_sock(&sock->sk); sock_put(&sock->sk); return; fail: /* Send DM */ nfc_llcp_send_dm(local, dsap, ssap, reason); } int nfc_llcp_queue_i_frames(struct nfc_llcp_sock *sock) { int nr_frames = 0; struct nfc_llcp_local *local = sock->local; pr_debug("Remote ready %d tx queue len %d remote rw %d", sock->remote_ready, skb_queue_len(&sock->tx_pending_queue), sock->remote_rw); /* Try to queue some I frames for transmission */ while (sock->remote_ready && skb_queue_len(&sock->tx_pending_queue) < sock->remote_rw) { struct sk_buff *pdu; pdu = skb_dequeue(&sock->tx_queue); if (pdu == NULL) break; /* Update N(S)/N(R) */ nfc_llcp_set_nrns(sock, pdu); skb_queue_tail(&local->tx_queue, pdu); nr_frames++; } return nr_frames; } static void nfc_llcp_recv_hdlc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap, ptype, ns, nr; ptype = nfc_llcp_ptype(skb); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); ns = nfc_llcp_ns(skb); nr = nfc_llcp_nr(skb); pr_debug("%d %d R %d S %d\n", dsap, ssap, nr, ns); llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); if (llcp_sock == NULL) { nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_sock_put(llcp_sock); } /* Pass the payload upstream */ if (ptype == LLCP_PDU_I) { pr_debug("I frame, queueing on %p\n", &llcp_sock->sk); if (ns == llcp_sock->recv_n) llcp_sock->recv_n = (llcp_sock->recv_n + 1) % 16; else pr_err("Received out of sequence I PDU\n"); skb_pull(skb, LLCP_HEADER_SIZE + LLCP_SEQUENCE_SIZE); if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) { /* * I frames will be freed from the socket layer, so we * need to keep them alive until someone receives them. */ skb_get(skb); } else { pr_err("Receive queue is full\n"); } } /* Remove skbs from the pending queue */ if (llcp_sock->send_ack_n != nr) { struct sk_buff *s, *tmp; u8 n; llcp_sock->send_ack_n = nr; /* Remove and free all skbs until ns == nr */ skb_queue_walk_safe(&llcp_sock->tx_pending_queue, s, tmp) { n = nfc_llcp_ns(s); skb_unlink(s, &llcp_sock->tx_pending_queue); kfree_skb(s); if (n == nr) break; } /* Re-queue the remaining skbs for transmission */ skb_queue_reverse_walk_safe(&llcp_sock->tx_pending_queue, s, tmp) { skb_unlink(s, &llcp_sock->tx_pending_queue); skb_queue_head(&local->tx_queue, s); } } if (ptype == LLCP_PDU_RR) llcp_sock->remote_ready = true; else if (ptype == LLCP_PDU_RNR) llcp_sock->remote_ready = false; if (nfc_llcp_queue_i_frames(llcp_sock) == 0 && ptype == LLCP_PDU_I) nfc_llcp_send_rr(llcp_sock); release_sock(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_disc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); if ((dsap == 0) && (ssap == 0)) { pr_debug("Connection termination"); nfc_dep_link_down(local->dev); return; } llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); if (llcp_sock == NULL) { nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_sock_put(llcp_sock); } if (sk->sk_state == LLCP_CONNECTED) { nfc_put_device(local->dev); sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); } nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_DISC); release_sock(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_cc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); llcp_sock = nfc_llcp_connecting_sock_get(local, dsap); if (llcp_sock == NULL) { pr_err("Invalid CC\n"); nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; /* Unlink from connecting and link to the client array */ nfc_llcp_sock_unlink(&local->connecting_sockets, sk); nfc_llcp_sock_link(&local->sockets, sk); llcp_sock->dsap = ssap; nfc_llcp_parse_connection_tlv(llcp_sock, &skb->data[LLCP_HEADER_SIZE], skb->len - LLCP_HEADER_SIZE); sk->sk_state = LLCP_CONNECTED; sk->sk_state_change(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_dm(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap, reason; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); reason = skb->data[2]; pr_debug("%d %d reason %d\n", ssap, dsap, reason); switch (reason) { case LLCP_DM_NOBOUND: case LLCP_DM_REJ: llcp_sock = nfc_llcp_connecting_sock_get(local, dsap); break; default: llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); break; } if (llcp_sock == NULL) { pr_debug("Already closed\n"); return; } sk = &llcp_sock->sk; sk->sk_err = ENXIO; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_snl(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; u8 dsap, ssap, *tlv, type, length, tid, sap; u16 tlv_len, offset; char *service_name; size_t service_name_len; struct nfc_llcp_sdp_tlv *sdp; HLIST_HEAD(llc_sdres_list); size_t sdres_tlvs_len; HLIST_HEAD(nl_sdres_list); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("%d %d\n", dsap, ssap); if (dsap != LLCP_SAP_SDP || ssap != LLCP_SAP_SDP) { pr_err("Wrong SNL SAP\n"); return; } tlv = &skb->data[LLCP_HEADER_SIZE]; tlv_len = skb->len - LLCP_HEADER_SIZE; offset = 0; sdres_tlvs_len = 0; while (offset < tlv_len) { type = tlv[0]; length = tlv[1]; switch (type) { case LLCP_TLV_SDREQ: tid = tlv[2]; service_name = (char *) &tlv[3]; service_name_len = length - 1; pr_debug("Looking for %.16s\n", service_name); if (service_name_len == strlen("urn:nfc:sn:sdp") && !strncmp(service_name, "urn:nfc:sn:sdp", service_name_len)) { sap = 1; goto add_snl; } llcp_sock = nfc_llcp_sock_from_sn(local, service_name, service_name_len); if (!llcp_sock) { sap = 0; goto add_snl; } /* * We found a socket but its ssap has not been reserved * yet. We need to assign it for good and send a reply. * The ssap will be freed when the socket is closed. */ if (llcp_sock->ssap == LLCP_SDP_UNBOUND) { atomic_t *client_count; sap = nfc_llcp_reserve_sdp_ssap(local); pr_debug("Reserving %d\n", sap); if (sap == LLCP_SAP_MAX) { sap = 0; goto add_snl; } client_count = &local->local_sdp_cnt[sap - LLCP_WKS_NUM_SAP]; atomic_inc(client_count); llcp_sock->ssap = sap; llcp_sock->reserved_ssap = sap; } else { sap = llcp_sock->ssap; } pr_debug("%p %d\n", llcp_sock, sap); add_snl: sdp = nfc_llcp_build_sdres_tlv(tid, sap); if (sdp == NULL) goto exit; sdres_tlvs_len += sdp->tlv_len; hlist_add_head(&sdp->node, &llc_sdres_list); break; case LLCP_TLV_SDRES: mutex_lock(&local->sdreq_lock); pr_debug("LLCP_TLV_SDRES: searching tid %d\n", tlv[2]); hlist_for_each_entry(sdp, &local->pending_sdreqs, node) { if (sdp->tid != tlv[2]) continue; sdp->sap = tlv[3]; pr_debug("Found: uri=%s, sap=%d\n", sdp->uri, sdp->sap); hlist_del(&sdp->node); hlist_add_head(&sdp->node, &nl_sdres_list); break; } mutex_unlock(&local->sdreq_lock); break; default: pr_err("Invalid SNL tlv value 0x%x\n", type); break; } offset += length + 2; tlv += length + 2; } exit: if (!hlist_empty(&nl_sdres_list)) nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list); if (!hlist_empty(&llc_sdres_list)) nfc_llcp_send_snl_sdres(local, &llc_sdres_list, sdres_tlvs_len); } static void nfc_llcp_recv_agf(struct nfc_llcp_local *local, struct sk_buff *skb) { u8 ptype; u16 pdu_len; struct sk_buff *new_skb; if (skb->len <= LLCP_HEADER_SIZE) { pr_err("Malformed AGF PDU\n"); return; } skb_pull(skb, LLCP_HEADER_SIZE); while (skb->len > LLCP_AGF_PDU_HEADER_SIZE) { pdu_len = skb->data[0] << 8 | skb->data[1]; skb_pull(skb, LLCP_AGF_PDU_HEADER_SIZE); if (pdu_len < LLCP_HEADER_SIZE || pdu_len > skb->len) { pr_err("Malformed AGF PDU\n"); return; } ptype = nfc_llcp_ptype(skb); if (ptype == LLCP_PDU_SYMM || ptype == LLCP_PDU_AGF) goto next; new_skb = nfc_alloc_recv_skb(pdu_len, GFP_KERNEL); if (new_skb == NULL) { pr_err("Could not allocate PDU\n"); return; } skb_put_data(new_skb, skb->data, pdu_len); nfc_llcp_rx_skb(local, new_skb); kfree_skb(new_skb); next: skb_pull(skb, pdu_len); } } static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb) { u8 dsap, ssap, ptype; ptype = nfc_llcp_ptype(skb); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("ptype 0x%x dsap 0x%x ssap 0x%x\n", ptype, dsap, ssap); if (ptype != LLCP_PDU_SYMM) print_hex_dump_debug("LLCP Rx: ", DUMP_PREFIX_OFFSET, 16, 1, skb->data, skb->len, true); switch (ptype) { case LLCP_PDU_SYMM: pr_debug("SYMM\n"); break; case LLCP_PDU_UI: pr_debug("UI\n"); nfc_llcp_recv_ui(local, skb); break; case LLCP_PDU_CONNECT: pr_debug("CONNECT\n"); nfc_llcp_recv_connect(local, skb); break; case LLCP_PDU_DISC: pr_debug("DISC\n"); nfc_llcp_recv_disc(local, skb); break; case LLCP_PDU_CC: pr_debug("CC\n"); nfc_llcp_recv_cc(local, skb); break; case LLCP_PDU_DM: pr_debug("DM\n"); nfc_llcp_recv_dm(local, skb); break; case LLCP_PDU_SNL: pr_debug("SNL\n"); nfc_llcp_recv_snl(local, skb); break; case LLCP_PDU_I: case LLCP_PDU_RR: case LLCP_PDU_RNR: pr_debug("I frame\n"); nfc_llcp_recv_hdlc(local, skb); break; case LLCP_PDU_AGF: pr_debug("AGF frame\n"); nfc_llcp_recv_agf(local, skb); break; } } static void nfc_llcp_rx_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, rx_work); struct sk_buff *skb; skb = local->rx_pending; if (skb == NULL) { pr_debug("No pending SKB\n"); return; } __net_timestamp(skb); nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_RX); nfc_llcp_rx_skb(local, skb); schedule_work(&local->tx_work); kfree_skb(local->rx_pending); local->rx_pending = NULL; } static void __nfc_llcp_recv(struct nfc_llcp_local *local, struct sk_buff *skb) { local->rx_pending = skb; del_timer(&local->link_timer); schedule_work(&local->rx_work); } void nfc_llcp_recv(void *data, struct sk_buff *skb, int err) { struct nfc_llcp_local *local = (struct nfc_llcp_local *) data; pr_debug("Received an LLCP PDU\n"); if (err < 0) { pr_err("err %d\n", err); return; } __nfc_llcp_recv(local, skb); } int nfc_llcp_data_received(struct nfc_dev *dev, struct sk_buff *skb) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) { kfree_skb(skb); return -ENODEV; } __nfc_llcp_recv(local, skb); return 0; } void nfc_llcp_mac_is_down(struct nfc_dev *dev) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) return; local->remote_miu = LLCP_DEFAULT_MIU; local->remote_lto = LLCP_DEFAULT_LTO; /* Close and purge all existing sockets */ nfc_llcp_socket_release(local, true, 0); } void nfc_llcp_mac_is_up(struct nfc_dev *dev, u32 target_idx, u8 comm_mode, u8 rf_mode) { struct nfc_llcp_local *local; pr_debug("rf mode %d\n", rf_mode); local = nfc_llcp_find_local(dev); if (local == NULL) return; local->target_idx = target_idx; local->comm_mode = comm_mode; local->rf_mode = rf_mode; if (rf_mode == NFC_RF_INITIATOR) { pr_debug("Queueing Tx work\n"); schedule_work(&local->tx_work); } else { mod_timer(&local->link_timer, jiffies + msecs_to_jiffies(local->remote_lto)); } } int nfc_llcp_register_device(struct nfc_dev *ndev) { struct nfc_llcp_local *local; local = kzalloc(sizeof(struct nfc_llcp_local), GFP_KERNEL); if (local == NULL) return -ENOMEM; local->dev = ndev; INIT_LIST_HEAD(&local->list); kref_init(&local->ref); mutex_init(&local->sdp_lock); timer_setup(&local->link_timer, nfc_llcp_symm_timer, 0); skb_queue_head_init(&local->tx_queue); INIT_WORK(&local->tx_work, nfc_llcp_tx_work); local->rx_pending = NULL; INIT_WORK(&local->rx_work, nfc_llcp_rx_work); INIT_WORK(&local->timeout_work, nfc_llcp_timeout_work); rwlock_init(&local->sockets.lock); rwlock_init(&local->connecting_sockets.lock); rwlock_init(&local->raw_sockets.lock); local->lto = 150; /* 1500 ms */ local->rw = LLCP_MAX_RW; local->miux = cpu_to_be16(LLCP_MAX_MIUX); local->local_wks = 0x1; /* LLC Link Management */ nfc_llcp_build_gb(local); local->remote_miu = LLCP_DEFAULT_MIU; local->remote_lto = LLCP_DEFAULT_LTO; mutex_init(&local->sdreq_lock); INIT_HLIST_HEAD(&local->pending_sdreqs); timer_setup(&local->sdreq_timer, nfc_llcp_sdreq_timer, 0); INIT_WORK(&local->sdreq_timeout_work, nfc_llcp_sdreq_timeout_work); list_add(&local->list, &llcp_devices); return 0; } void nfc_llcp_unregister_device(struct nfc_dev *dev) { struct nfc_llcp_local *local = nfc_llcp_find_local(dev); if (local == NULL) { pr_debug("No such device\n"); return; } local_cleanup(local); nfc_llcp_local_put(local); } int __init nfc_llcp_init(void) { return nfc_llcp_sock_init(); } void nfc_llcp_exit(void) { nfc_llcp_sock_exit(); }
/* * Copyright (C) 2011 Intel Corporation. All rights reserved. * Copyright (C) 2014 Marvell International Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #define pr_fmt(fmt) "llcp: %s: " fmt, __func__ #include <linux/init.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/nfc.h> #include "nfc.h" #include "llcp.h" static u8 llcp_magic[3] = {0x46, 0x66, 0x6d}; static LIST_HEAD(llcp_devices); static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb); void nfc_llcp_sock_link(struct llcp_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } void nfc_llcp_sock_unlink(struct llcp_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } void nfc_llcp_socket_remote_param_init(struct nfc_llcp_sock *sock) { sock->remote_rw = LLCP_DEFAULT_RW; sock->remote_miu = LLCP_MAX_MIU + 1; } static void nfc_llcp_socket_purge(struct nfc_llcp_sock *sock) { struct nfc_llcp_local *local = sock->local; struct sk_buff *s, *tmp; pr_debug("%p\n", &sock->sk); skb_queue_purge(&sock->tx_queue); skb_queue_purge(&sock->tx_pending_queue); if (local == NULL) return; /* Search for local pending SKBs that are related to this socket */ skb_queue_walk_safe(&local->tx_queue, s, tmp) { if (s->sk != &sock->sk) continue; skb_unlink(s, &local->tx_queue); kfree_skb(s); } } static void nfc_llcp_socket_release(struct nfc_llcp_local *local, bool device, int err) { struct sock *sk; struct hlist_node *tmp; struct nfc_llcp_sock *llcp_sock; skb_queue_purge(&local->tx_queue); write_lock(&local->sockets.lock); sk_for_each_safe(sk, tmp, &local->sockets.head) { llcp_sock = nfc_llcp_sock(sk); bh_lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (sk->sk_state == LLCP_CONNECTED) nfc_put_device(llcp_sock->dev); if (sk->sk_state == LLCP_LISTEN) { struct nfc_llcp_sock *lsk, *n; struct sock *accept_sk; list_for_each_entry_safe(lsk, n, &llcp_sock->accept_queue, accept_queue) { accept_sk = &lsk->sk; bh_lock_sock(accept_sk); nfc_llcp_accept_unlink(accept_sk); if (err) accept_sk->sk_err = err; accept_sk->sk_state = LLCP_CLOSED; accept_sk->sk_state_change(sk); bh_unlock_sock(accept_sk); } } if (err) sk->sk_err = err; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); bh_unlock_sock(sk); sk_del_node_init(sk); } write_unlock(&local->sockets.lock); /* If we still have a device, we keep the RAW sockets alive */ if (device == true) return; write_lock(&local->raw_sockets.lock); sk_for_each_safe(sk, tmp, &local->raw_sockets.head) { llcp_sock = nfc_llcp_sock(sk); bh_lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (err) sk->sk_err = err; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); bh_unlock_sock(sk); sk_del_node_init(sk); } write_unlock(&local->raw_sockets.lock); } struct nfc_llcp_local *nfc_llcp_local_get(struct nfc_llcp_local *local) { kref_get(&local->ref); return local; } static void local_cleanup(struct nfc_llcp_local *local) { nfc_llcp_socket_release(local, false, ENXIO); del_timer_sync(&local->link_timer); skb_queue_purge(&local->tx_queue); cancel_work_sync(&local->tx_work); cancel_work_sync(&local->rx_work); cancel_work_sync(&local->timeout_work); kfree_skb(local->rx_pending); del_timer_sync(&local->sdreq_timer); cancel_work_sync(&local->sdreq_timeout_work); nfc_llcp_free_sdp_tlv_list(&local->pending_sdreqs); } static void local_release(struct kref *ref) { struct nfc_llcp_local *local; local = container_of(ref, struct nfc_llcp_local, ref); list_del(&local->list); local_cleanup(local); kfree(local); } int nfc_llcp_local_put(struct nfc_llcp_local *local) { if (local == NULL) return 0; return kref_put(&local->ref, local_release); } static struct nfc_llcp_sock *nfc_llcp_sock_get(struct nfc_llcp_local *local, u8 ssap, u8 dsap) { struct sock *sk; struct nfc_llcp_sock *llcp_sock, *tmp_sock; pr_debug("ssap dsap %d %d\n", ssap, dsap); if (ssap == 0 && dsap == 0) return NULL; read_lock(&local->sockets.lock); llcp_sock = NULL; sk_for_each(sk, &local->sockets.head) { tmp_sock = nfc_llcp_sock(sk); if (tmp_sock->ssap == ssap && tmp_sock->dsap == dsap) { llcp_sock = tmp_sock; break; } } read_unlock(&local->sockets.lock); if (llcp_sock == NULL) return NULL; sock_hold(&llcp_sock->sk); return llcp_sock; } static void nfc_llcp_sock_put(struct nfc_llcp_sock *sock) { sock_put(&sock->sk); } static void nfc_llcp_timeout_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, timeout_work); nfc_dep_link_down(local->dev); } static void nfc_llcp_symm_timer(struct timer_list *t) { struct nfc_llcp_local *local = from_timer(local, t, link_timer); pr_err("SYMM timeout\n"); schedule_work(&local->timeout_work); } static void nfc_llcp_sdreq_timeout_work(struct work_struct *work) { unsigned long time; HLIST_HEAD(nl_sdres_list); struct hlist_node *n; struct nfc_llcp_sdp_tlv *sdp; struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, sdreq_timeout_work); mutex_lock(&local->sdreq_lock); time = jiffies - msecs_to_jiffies(3 * local->remote_lto); hlist_for_each_entry_safe(sdp, n, &local->pending_sdreqs, node) { if (time_after(sdp->time, time)) continue; sdp->sap = LLCP_SDP_UNBOUND; hlist_del(&sdp->node); hlist_add_head(&sdp->node, &nl_sdres_list); } if (!hlist_empty(&local->pending_sdreqs)) mod_timer(&local->sdreq_timer, jiffies + msecs_to_jiffies(3 * local->remote_lto)); mutex_unlock(&local->sdreq_lock); if (!hlist_empty(&nl_sdres_list)) nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list); } static void nfc_llcp_sdreq_timer(struct timer_list *t) { struct nfc_llcp_local *local = from_timer(local, t, sdreq_timer); schedule_work(&local->sdreq_timeout_work); } struct nfc_llcp_local *nfc_llcp_find_local(struct nfc_dev *dev) { struct nfc_llcp_local *local; list_for_each_entry(local, &llcp_devices, list) if (local->dev == dev) return local; pr_debug("No device found\n"); return NULL; } static char *wks[] = { NULL, NULL, /* SDP */ "urn:nfc:sn:ip", "urn:nfc:sn:obex", "urn:nfc:sn:snep", }; static int nfc_llcp_wks_sap(char *service_name, size_t service_name_len) { int sap, num_wks; pr_debug("%s\n", service_name); if (service_name == NULL) return -EINVAL; num_wks = ARRAY_SIZE(wks); for (sap = 0; sap < num_wks; sap++) { if (wks[sap] == NULL) continue; if (strncmp(wks[sap], service_name, service_name_len) == 0) return sap; } return -EINVAL; } static struct nfc_llcp_sock *nfc_llcp_sock_from_sn(struct nfc_llcp_local *local, u8 *sn, size_t sn_len) { struct sock *sk; struct nfc_llcp_sock *llcp_sock, *tmp_sock; pr_debug("sn %zd %p\n", sn_len, sn); if (sn == NULL || sn_len == 0) return NULL; read_lock(&local->sockets.lock); llcp_sock = NULL; sk_for_each(sk, &local->sockets.head) { tmp_sock = nfc_llcp_sock(sk); pr_debug("llcp sock %p\n", tmp_sock); if (tmp_sock->sk.sk_type == SOCK_STREAM && tmp_sock->sk.sk_state != LLCP_LISTEN) continue; if (tmp_sock->sk.sk_type == SOCK_DGRAM && tmp_sock->sk.sk_state != LLCP_BOUND) continue; if (tmp_sock->service_name == NULL || tmp_sock->service_name_len == 0) continue; if (tmp_sock->service_name_len != sn_len) continue; if (memcmp(sn, tmp_sock->service_name, sn_len) == 0) { llcp_sock = tmp_sock; break; } } read_unlock(&local->sockets.lock); pr_debug("Found llcp sock %p\n", llcp_sock); return llcp_sock; } u8 nfc_llcp_get_sdp_ssap(struct nfc_llcp_local *local, struct nfc_llcp_sock *sock) { mutex_lock(&local->sdp_lock); if (sock->service_name != NULL && sock->service_name_len > 0) { int ssap = nfc_llcp_wks_sap(sock->service_name, sock->service_name_len); if (ssap > 0) { pr_debug("WKS %d\n", ssap); /* This is a WKS, let's check if it's free */ if (local->local_wks & BIT(ssap)) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } set_bit(ssap, &local->local_wks); mutex_unlock(&local->sdp_lock); return ssap; } /* * Check if there already is a non WKS socket bound * to this service name. */ if (nfc_llcp_sock_from_sn(local, sock->service_name, sock->service_name_len) != NULL) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } mutex_unlock(&local->sdp_lock); return LLCP_SDP_UNBOUND; } else if (sock->ssap != 0 && sock->ssap < LLCP_WKS_NUM_SAP) { if (!test_bit(sock->ssap, &local->local_wks)) { set_bit(sock->ssap, &local->local_wks); mutex_unlock(&local->sdp_lock); return sock->ssap; } } mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } u8 nfc_llcp_get_local_ssap(struct nfc_llcp_local *local) { u8 local_ssap; mutex_lock(&local->sdp_lock); local_ssap = find_first_zero_bit(&local->local_sap, LLCP_LOCAL_NUM_SAP); if (local_ssap == LLCP_LOCAL_NUM_SAP) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } set_bit(local_ssap, &local->local_sap); mutex_unlock(&local->sdp_lock); return local_ssap + LLCP_LOCAL_SAP_OFFSET; } void nfc_llcp_put_ssap(struct nfc_llcp_local *local, u8 ssap) { u8 local_ssap; unsigned long *sdp; if (ssap < LLCP_WKS_NUM_SAP) { local_ssap = ssap; sdp = &local->local_wks; } else if (ssap < LLCP_LOCAL_NUM_SAP) { atomic_t *client_cnt; local_ssap = ssap - LLCP_WKS_NUM_SAP; sdp = &local->local_sdp; client_cnt = &local->local_sdp_cnt[local_ssap]; pr_debug("%d clients\n", atomic_read(client_cnt)); mutex_lock(&local->sdp_lock); if (atomic_dec_and_test(client_cnt)) { struct nfc_llcp_sock *l_sock; pr_debug("No more clients for SAP %d\n", ssap); clear_bit(local_ssap, sdp); /* Find the listening sock and set it back to UNBOUND */ l_sock = nfc_llcp_sock_get(local, ssap, LLCP_SAP_SDP); if (l_sock) { l_sock->ssap = LLCP_SDP_UNBOUND; nfc_llcp_sock_put(l_sock); } } mutex_unlock(&local->sdp_lock); return; } else if (ssap < LLCP_MAX_SAP) { local_ssap = ssap - LLCP_LOCAL_NUM_SAP; sdp = &local->local_sap; } else { return; } mutex_lock(&local->sdp_lock); clear_bit(local_ssap, sdp); mutex_unlock(&local->sdp_lock); } static u8 nfc_llcp_reserve_sdp_ssap(struct nfc_llcp_local *local) { u8 ssap; mutex_lock(&local->sdp_lock); ssap = find_first_zero_bit(&local->local_sdp, LLCP_SDP_NUM_SAP); if (ssap == LLCP_SDP_NUM_SAP) { mutex_unlock(&local->sdp_lock); return LLCP_SAP_MAX; } pr_debug("SDP ssap %d\n", LLCP_WKS_NUM_SAP + ssap); set_bit(ssap, &local->local_sdp); mutex_unlock(&local->sdp_lock); return LLCP_WKS_NUM_SAP + ssap; } static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, version, version_length; u8 lto_length, wks_length, miux_length; u8 *version_tlv = NULL, *lto_tlv = NULL, *wks_tlv = NULL, *miux_tlv = NULL; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); if (!version_tlv) { ret = -ENOMEM; goto out; } gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); if (!lto_tlv) { ret = -ENOMEM; goto out; } gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); if (!wks_tlv) { ret = -ENOMEM; goto out; } gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); if (!miux_tlv) { ret = -ENOMEM; goto out; } gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; } u8 *nfc_llcp_general_bytes(struct nfc_dev *dev, size_t *general_bytes_len) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) { *general_bytes_len = 0; return NULL; } nfc_llcp_build_gb(local); *general_bytes_len = local->gb_len; return local->gb; } int nfc_llcp_set_remote_gb(struct nfc_dev *dev, u8 *gb, u8 gb_len) { struct nfc_llcp_local *local; if (gb_len < 3 || gb_len > NFC_MAX_GT_LEN) return -EINVAL; local = nfc_llcp_find_local(dev); if (local == NULL) { pr_err("No LLCP device\n"); return -ENODEV; } memset(local->remote_gb, 0, NFC_MAX_GT_LEN); memcpy(local->remote_gb, gb, gb_len); local->remote_gb_len = gb_len; if (memcmp(local->remote_gb, llcp_magic, 3)) { pr_err("MAC does not support LLCP\n"); return -EINVAL; } return nfc_llcp_parse_gb_tlv(local, &local->remote_gb[3], local->remote_gb_len - 3); } static u8 nfc_llcp_dsap(struct sk_buff *pdu) { return (pdu->data[0] & 0xfc) >> 2; } static u8 nfc_llcp_ptype(struct sk_buff *pdu) { return ((pdu->data[0] & 0x03) << 2) | ((pdu->data[1] & 0xc0) >> 6); } static u8 nfc_llcp_ssap(struct sk_buff *pdu) { return pdu->data[1] & 0x3f; } static u8 nfc_llcp_ns(struct sk_buff *pdu) { return pdu->data[2] >> 4; } static u8 nfc_llcp_nr(struct sk_buff *pdu) { return pdu->data[2] & 0xf; } static void nfc_llcp_set_nrns(struct nfc_llcp_sock *sock, struct sk_buff *pdu) { pdu->data[2] = (sock->send_n << 4) | (sock->recv_n); sock->send_n = (sock->send_n + 1) % 16; sock->recv_ack_n = (sock->recv_n - 1) % 16; } void nfc_llcp_send_to_raw_sock(struct nfc_llcp_local *local, struct sk_buff *skb, u8 direction) { struct sk_buff *skb_copy = NULL, *nskb; struct sock *sk; u8 *data; read_lock(&local->raw_sockets.lock); sk_for_each(sk, &local->raw_sockets.head) { if (sk->sk_state != LLCP_BOUND) continue; if (skb_copy == NULL) { skb_copy = __pskb_copy_fclone(skb, NFC_RAW_HEADER_SIZE, GFP_ATOMIC, true); if (skb_copy == NULL) continue; data = skb_push(skb_copy, NFC_RAW_HEADER_SIZE); data[0] = local->dev ? local->dev->idx : 0xFF; data[1] = direction & 0x01; data[1] |= (RAW_PAYLOAD_LLCP << 1); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&local->raw_sockets.lock); kfree_skb(skb_copy); } static void nfc_llcp_tx_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, tx_work); struct sk_buff *skb; struct sock *sk; struct nfc_llcp_sock *llcp_sock; skb = skb_dequeue(&local->tx_queue); if (skb != NULL) { sk = skb->sk; llcp_sock = nfc_llcp_sock(sk); if (llcp_sock == NULL && nfc_llcp_ptype(skb) == LLCP_PDU_I) { kfree_skb(skb); nfc_llcp_send_symm(local->dev); } else if (llcp_sock && !llcp_sock->remote_ready) { skb_queue_head(&local->tx_queue, skb); nfc_llcp_send_symm(local->dev); } else { struct sk_buff *copy_skb = NULL; u8 ptype = nfc_llcp_ptype(skb); int ret; pr_debug("Sending pending skb\n"); print_hex_dump_debug("LLCP Tx: ", DUMP_PREFIX_OFFSET, 16, 1, skb->data, skb->len, true); if (ptype == LLCP_PDU_DISC && sk != NULL && sk->sk_state == LLCP_DISCONNECTING) { nfc_llcp_sock_unlink(&local->sockets, sk); sock_orphan(sk); sock_put(sk); } if (ptype == LLCP_PDU_I) copy_skb = skb_copy(skb, GFP_ATOMIC); __net_timestamp(skb); nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_TX); ret = nfc_data_exchange(local->dev, local->target_idx, skb, nfc_llcp_recv, local); if (ret) { kfree_skb(copy_skb); goto out; } if (ptype == LLCP_PDU_I && copy_skb) skb_queue_tail(&llcp_sock->tx_pending_queue, copy_skb); } } else { nfc_llcp_send_symm(local->dev); } out: mod_timer(&local->link_timer, jiffies + msecs_to_jiffies(2 * local->remote_lto)); } static struct nfc_llcp_sock *nfc_llcp_connecting_sock_get(struct nfc_llcp_local *local, u8 ssap) { struct sock *sk; struct nfc_llcp_sock *llcp_sock; read_lock(&local->connecting_sockets.lock); sk_for_each(sk, &local->connecting_sockets.head) { llcp_sock = nfc_llcp_sock(sk); if (llcp_sock->ssap == ssap) { sock_hold(&llcp_sock->sk); goto out; } } llcp_sock = NULL; out: read_unlock(&local->connecting_sockets.lock); return llcp_sock; } static struct nfc_llcp_sock *nfc_llcp_sock_get_sn(struct nfc_llcp_local *local, u8 *sn, size_t sn_len) { struct nfc_llcp_sock *llcp_sock; llcp_sock = nfc_llcp_sock_from_sn(local, sn, sn_len); if (llcp_sock == NULL) return NULL; sock_hold(&llcp_sock->sk); return llcp_sock; } static u8 *nfc_llcp_connect_sn(struct sk_buff *skb, size_t *sn_len) { u8 *tlv = &skb->data[2], type, length; size_t tlv_array_len = skb->len - LLCP_HEADER_SIZE, offset = 0; while (offset < tlv_array_len) { type = tlv[0]; length = tlv[1]; pr_debug("type 0x%x length %d\n", type, length); if (type == LLCP_TLV_SN) { *sn_len = length; return &tlv[2]; } offset += length + 2; tlv += length + 2; } return NULL; } static void nfc_llcp_recv_ui(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct nfc_llcp_ui_cb *ui_cb; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); ui_cb = nfc_llcp_ui_skb_cb(skb); ui_cb->dsap = dsap; ui_cb->ssap = ssap; pr_debug("%d %d\n", dsap, ssap); /* We're looking for a bound socket, not a client one */ llcp_sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP); if (llcp_sock == NULL || llcp_sock->sk.sk_type != SOCK_DGRAM) return; /* There is no sequence with UI frames */ skb_pull(skb, LLCP_HEADER_SIZE); if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) { /* * UI frames will be freed from the socket layer, so we * need to keep them alive until someone receives them. */ skb_get(skb); } else { pr_err("Receive queue is full\n"); } nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_connect(struct nfc_llcp_local *local, struct sk_buff *skb) { struct sock *new_sk, *parent; struct nfc_llcp_sock *sock, *new_sock; u8 dsap, ssap, reason; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("%d %d\n", dsap, ssap); if (dsap != LLCP_SAP_SDP) { sock = nfc_llcp_sock_get(local, dsap, LLCP_SAP_SDP); if (sock == NULL || sock->sk.sk_state != LLCP_LISTEN) { reason = LLCP_DM_NOBOUND; goto fail; } } else { u8 *sn; size_t sn_len; sn = nfc_llcp_connect_sn(skb, &sn_len); if (sn == NULL) { reason = LLCP_DM_NOBOUND; goto fail; } pr_debug("Service name length %zu\n", sn_len); sock = nfc_llcp_sock_get_sn(local, sn, sn_len); if (sock == NULL) { reason = LLCP_DM_NOBOUND; goto fail; } } lock_sock(&sock->sk); parent = &sock->sk; if (sk_acceptq_is_full(parent)) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } if (sock->ssap == LLCP_SDP_UNBOUND) { u8 ssap = nfc_llcp_reserve_sdp_ssap(local); pr_debug("First client, reserving %d\n", ssap); if (ssap == LLCP_SAP_MAX) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } sock->ssap = ssap; } new_sk = nfc_llcp_sock_alloc(NULL, parent->sk_type, GFP_ATOMIC, 0); if (new_sk == NULL) { reason = LLCP_DM_REJ; release_sock(&sock->sk); sock_put(&sock->sk); goto fail; } new_sock = nfc_llcp_sock(new_sk); new_sock->dev = local->dev; new_sock->local = nfc_llcp_local_get(local); new_sock->rw = sock->rw; new_sock->miux = sock->miux; new_sock->nfc_protocol = sock->nfc_protocol; new_sock->dsap = ssap; new_sock->target_idx = local->target_idx; new_sock->parent = parent; new_sock->ssap = sock->ssap; if (sock->ssap < LLCP_LOCAL_NUM_SAP && sock->ssap >= LLCP_WKS_NUM_SAP) { atomic_t *client_count; pr_debug("reserved_ssap %d for %p\n", sock->ssap, new_sock); client_count = &local->local_sdp_cnt[sock->ssap - LLCP_WKS_NUM_SAP]; atomic_inc(client_count); new_sock->reserved_ssap = sock->ssap; } nfc_llcp_parse_connection_tlv(new_sock, &skb->data[LLCP_HEADER_SIZE], skb->len - LLCP_HEADER_SIZE); pr_debug("new sock %p sk %p\n", new_sock, &new_sock->sk); nfc_llcp_sock_link(&local->sockets, new_sk); nfc_llcp_accept_enqueue(&sock->sk, new_sk); nfc_get_device(local->dev->idx); new_sk->sk_state = LLCP_CONNECTED; /* Wake the listening processes */ parent->sk_data_ready(parent); /* Send CC */ nfc_llcp_send_cc(new_sock); release_sock(&sock->sk); sock_put(&sock->sk); return; fail: /* Send DM */ nfc_llcp_send_dm(local, dsap, ssap, reason); } int nfc_llcp_queue_i_frames(struct nfc_llcp_sock *sock) { int nr_frames = 0; struct nfc_llcp_local *local = sock->local; pr_debug("Remote ready %d tx queue len %d remote rw %d", sock->remote_ready, skb_queue_len(&sock->tx_pending_queue), sock->remote_rw); /* Try to queue some I frames for transmission */ while (sock->remote_ready && skb_queue_len(&sock->tx_pending_queue) < sock->remote_rw) { struct sk_buff *pdu; pdu = skb_dequeue(&sock->tx_queue); if (pdu == NULL) break; /* Update N(S)/N(R) */ nfc_llcp_set_nrns(sock, pdu); skb_queue_tail(&local->tx_queue, pdu); nr_frames++; } return nr_frames; } static void nfc_llcp_recv_hdlc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap, ptype, ns, nr; ptype = nfc_llcp_ptype(skb); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); ns = nfc_llcp_ns(skb); nr = nfc_llcp_nr(skb); pr_debug("%d %d R %d S %d\n", dsap, ssap, nr, ns); llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); if (llcp_sock == NULL) { nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_sock_put(llcp_sock); } /* Pass the payload upstream */ if (ptype == LLCP_PDU_I) { pr_debug("I frame, queueing on %p\n", &llcp_sock->sk); if (ns == llcp_sock->recv_n) llcp_sock->recv_n = (llcp_sock->recv_n + 1) % 16; else pr_err("Received out of sequence I PDU\n"); skb_pull(skb, LLCP_HEADER_SIZE + LLCP_SEQUENCE_SIZE); if (!sock_queue_rcv_skb(&llcp_sock->sk, skb)) { /* * I frames will be freed from the socket layer, so we * need to keep them alive until someone receives them. */ skb_get(skb); } else { pr_err("Receive queue is full\n"); } } /* Remove skbs from the pending queue */ if (llcp_sock->send_ack_n != nr) { struct sk_buff *s, *tmp; u8 n; llcp_sock->send_ack_n = nr; /* Remove and free all skbs until ns == nr */ skb_queue_walk_safe(&llcp_sock->tx_pending_queue, s, tmp) { n = nfc_llcp_ns(s); skb_unlink(s, &llcp_sock->tx_pending_queue); kfree_skb(s); if (n == nr) break; } /* Re-queue the remaining skbs for transmission */ skb_queue_reverse_walk_safe(&llcp_sock->tx_pending_queue, s, tmp) { skb_unlink(s, &llcp_sock->tx_pending_queue); skb_queue_head(&local->tx_queue, s); } } if (ptype == LLCP_PDU_RR) llcp_sock->remote_ready = true; else if (ptype == LLCP_PDU_RNR) llcp_sock->remote_ready = false; if (nfc_llcp_queue_i_frames(llcp_sock) == 0 && ptype == LLCP_PDU_I) nfc_llcp_send_rr(llcp_sock); release_sock(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_disc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); if ((dsap == 0) && (ssap == 0)) { pr_debug("Connection termination"); nfc_dep_link_down(local->dev); return; } llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); if (llcp_sock == NULL) { nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; lock_sock(sk); nfc_llcp_socket_purge(llcp_sock); if (sk->sk_state == LLCP_CLOSED) { release_sock(sk); nfc_llcp_sock_put(llcp_sock); } if (sk->sk_state == LLCP_CONNECTED) { nfc_put_device(local->dev); sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); } nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_DISC); release_sock(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_cc(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); llcp_sock = nfc_llcp_connecting_sock_get(local, dsap); if (llcp_sock == NULL) { pr_err("Invalid CC\n"); nfc_llcp_send_dm(local, dsap, ssap, LLCP_DM_NOCONN); return; } sk = &llcp_sock->sk; /* Unlink from connecting and link to the client array */ nfc_llcp_sock_unlink(&local->connecting_sockets, sk); nfc_llcp_sock_link(&local->sockets, sk); llcp_sock->dsap = ssap; nfc_llcp_parse_connection_tlv(llcp_sock, &skb->data[LLCP_HEADER_SIZE], skb->len - LLCP_HEADER_SIZE); sk->sk_state = LLCP_CONNECTED; sk->sk_state_change(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_dm(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; struct sock *sk; u8 dsap, ssap, reason; dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); reason = skb->data[2]; pr_debug("%d %d reason %d\n", ssap, dsap, reason); switch (reason) { case LLCP_DM_NOBOUND: case LLCP_DM_REJ: llcp_sock = nfc_llcp_connecting_sock_get(local, dsap); break; default: llcp_sock = nfc_llcp_sock_get(local, dsap, ssap); break; } if (llcp_sock == NULL) { pr_debug("Already closed\n"); return; } sk = &llcp_sock->sk; sk->sk_err = ENXIO; sk->sk_state = LLCP_CLOSED; sk->sk_state_change(sk); nfc_llcp_sock_put(llcp_sock); } static void nfc_llcp_recv_snl(struct nfc_llcp_local *local, struct sk_buff *skb) { struct nfc_llcp_sock *llcp_sock; u8 dsap, ssap, *tlv, type, length, tid, sap; u16 tlv_len, offset; char *service_name; size_t service_name_len; struct nfc_llcp_sdp_tlv *sdp; HLIST_HEAD(llc_sdres_list); size_t sdres_tlvs_len; HLIST_HEAD(nl_sdres_list); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("%d %d\n", dsap, ssap); if (dsap != LLCP_SAP_SDP || ssap != LLCP_SAP_SDP) { pr_err("Wrong SNL SAP\n"); return; } tlv = &skb->data[LLCP_HEADER_SIZE]; tlv_len = skb->len - LLCP_HEADER_SIZE; offset = 0; sdres_tlvs_len = 0; while (offset < tlv_len) { type = tlv[0]; length = tlv[1]; switch (type) { case LLCP_TLV_SDREQ: tid = tlv[2]; service_name = (char *) &tlv[3]; service_name_len = length - 1; pr_debug("Looking for %.16s\n", service_name); if (service_name_len == strlen("urn:nfc:sn:sdp") && !strncmp(service_name, "urn:nfc:sn:sdp", service_name_len)) { sap = 1; goto add_snl; } llcp_sock = nfc_llcp_sock_from_sn(local, service_name, service_name_len); if (!llcp_sock) { sap = 0; goto add_snl; } /* * We found a socket but its ssap has not been reserved * yet. We need to assign it for good and send a reply. * The ssap will be freed when the socket is closed. */ if (llcp_sock->ssap == LLCP_SDP_UNBOUND) { atomic_t *client_count; sap = nfc_llcp_reserve_sdp_ssap(local); pr_debug("Reserving %d\n", sap); if (sap == LLCP_SAP_MAX) { sap = 0; goto add_snl; } client_count = &local->local_sdp_cnt[sap - LLCP_WKS_NUM_SAP]; atomic_inc(client_count); llcp_sock->ssap = sap; llcp_sock->reserved_ssap = sap; } else { sap = llcp_sock->ssap; } pr_debug("%p %d\n", llcp_sock, sap); add_snl: sdp = nfc_llcp_build_sdres_tlv(tid, sap); if (sdp == NULL) goto exit; sdres_tlvs_len += sdp->tlv_len; hlist_add_head(&sdp->node, &llc_sdres_list); break; case LLCP_TLV_SDRES: mutex_lock(&local->sdreq_lock); pr_debug("LLCP_TLV_SDRES: searching tid %d\n", tlv[2]); hlist_for_each_entry(sdp, &local->pending_sdreqs, node) { if (sdp->tid != tlv[2]) continue; sdp->sap = tlv[3]; pr_debug("Found: uri=%s, sap=%d\n", sdp->uri, sdp->sap); hlist_del(&sdp->node); hlist_add_head(&sdp->node, &nl_sdres_list); break; } mutex_unlock(&local->sdreq_lock); break; default: pr_err("Invalid SNL tlv value 0x%x\n", type); break; } offset += length + 2; tlv += length + 2; } exit: if (!hlist_empty(&nl_sdres_list)) nfc_genl_llc_send_sdres(local->dev, &nl_sdres_list); if (!hlist_empty(&llc_sdres_list)) nfc_llcp_send_snl_sdres(local, &llc_sdres_list, sdres_tlvs_len); } static void nfc_llcp_recv_agf(struct nfc_llcp_local *local, struct sk_buff *skb) { u8 ptype; u16 pdu_len; struct sk_buff *new_skb; if (skb->len <= LLCP_HEADER_SIZE) { pr_err("Malformed AGF PDU\n"); return; } skb_pull(skb, LLCP_HEADER_SIZE); while (skb->len > LLCP_AGF_PDU_HEADER_SIZE) { pdu_len = skb->data[0] << 8 | skb->data[1]; skb_pull(skb, LLCP_AGF_PDU_HEADER_SIZE); if (pdu_len < LLCP_HEADER_SIZE || pdu_len > skb->len) { pr_err("Malformed AGF PDU\n"); return; } ptype = nfc_llcp_ptype(skb); if (ptype == LLCP_PDU_SYMM || ptype == LLCP_PDU_AGF) goto next; new_skb = nfc_alloc_recv_skb(pdu_len, GFP_KERNEL); if (new_skb == NULL) { pr_err("Could not allocate PDU\n"); return; } skb_put_data(new_skb, skb->data, pdu_len); nfc_llcp_rx_skb(local, new_skb); kfree_skb(new_skb); next: skb_pull(skb, pdu_len); } } static void nfc_llcp_rx_skb(struct nfc_llcp_local *local, struct sk_buff *skb) { u8 dsap, ssap, ptype; ptype = nfc_llcp_ptype(skb); dsap = nfc_llcp_dsap(skb); ssap = nfc_llcp_ssap(skb); pr_debug("ptype 0x%x dsap 0x%x ssap 0x%x\n", ptype, dsap, ssap); if (ptype != LLCP_PDU_SYMM) print_hex_dump_debug("LLCP Rx: ", DUMP_PREFIX_OFFSET, 16, 1, skb->data, skb->len, true); switch (ptype) { case LLCP_PDU_SYMM: pr_debug("SYMM\n"); break; case LLCP_PDU_UI: pr_debug("UI\n"); nfc_llcp_recv_ui(local, skb); break; case LLCP_PDU_CONNECT: pr_debug("CONNECT\n"); nfc_llcp_recv_connect(local, skb); break; case LLCP_PDU_DISC: pr_debug("DISC\n"); nfc_llcp_recv_disc(local, skb); break; case LLCP_PDU_CC: pr_debug("CC\n"); nfc_llcp_recv_cc(local, skb); break; case LLCP_PDU_DM: pr_debug("DM\n"); nfc_llcp_recv_dm(local, skb); break; case LLCP_PDU_SNL: pr_debug("SNL\n"); nfc_llcp_recv_snl(local, skb); break; case LLCP_PDU_I: case LLCP_PDU_RR: case LLCP_PDU_RNR: pr_debug("I frame\n"); nfc_llcp_recv_hdlc(local, skb); break; case LLCP_PDU_AGF: pr_debug("AGF frame\n"); nfc_llcp_recv_agf(local, skb); break; } } static void nfc_llcp_rx_work(struct work_struct *work) { struct nfc_llcp_local *local = container_of(work, struct nfc_llcp_local, rx_work); struct sk_buff *skb; skb = local->rx_pending; if (skb == NULL) { pr_debug("No pending SKB\n"); return; } __net_timestamp(skb); nfc_llcp_send_to_raw_sock(local, skb, NFC_DIRECTION_RX); nfc_llcp_rx_skb(local, skb); schedule_work(&local->tx_work); kfree_skb(local->rx_pending); local->rx_pending = NULL; } static void __nfc_llcp_recv(struct nfc_llcp_local *local, struct sk_buff *skb) { local->rx_pending = skb; del_timer(&local->link_timer); schedule_work(&local->rx_work); } void nfc_llcp_recv(void *data, struct sk_buff *skb, int err) { struct nfc_llcp_local *local = (struct nfc_llcp_local *) data; pr_debug("Received an LLCP PDU\n"); if (err < 0) { pr_err("err %d\n", err); return; } __nfc_llcp_recv(local, skb); } int nfc_llcp_data_received(struct nfc_dev *dev, struct sk_buff *skb) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) { kfree_skb(skb); return -ENODEV; } __nfc_llcp_recv(local, skb); return 0; } void nfc_llcp_mac_is_down(struct nfc_dev *dev) { struct nfc_llcp_local *local; local = nfc_llcp_find_local(dev); if (local == NULL) return; local->remote_miu = LLCP_DEFAULT_MIU; local->remote_lto = LLCP_DEFAULT_LTO; /* Close and purge all existing sockets */ nfc_llcp_socket_release(local, true, 0); } void nfc_llcp_mac_is_up(struct nfc_dev *dev, u32 target_idx, u8 comm_mode, u8 rf_mode) { struct nfc_llcp_local *local; pr_debug("rf mode %d\n", rf_mode); local = nfc_llcp_find_local(dev); if (local == NULL) return; local->target_idx = target_idx; local->comm_mode = comm_mode; local->rf_mode = rf_mode; if (rf_mode == NFC_RF_INITIATOR) { pr_debug("Queueing Tx work\n"); schedule_work(&local->tx_work); } else { mod_timer(&local->link_timer, jiffies + msecs_to_jiffies(local->remote_lto)); } } int nfc_llcp_register_device(struct nfc_dev *ndev) { struct nfc_llcp_local *local; local = kzalloc(sizeof(struct nfc_llcp_local), GFP_KERNEL); if (local == NULL) return -ENOMEM; local->dev = ndev; INIT_LIST_HEAD(&local->list); kref_init(&local->ref); mutex_init(&local->sdp_lock); timer_setup(&local->link_timer, nfc_llcp_symm_timer, 0); skb_queue_head_init(&local->tx_queue); INIT_WORK(&local->tx_work, nfc_llcp_tx_work); local->rx_pending = NULL; INIT_WORK(&local->rx_work, nfc_llcp_rx_work); INIT_WORK(&local->timeout_work, nfc_llcp_timeout_work); rwlock_init(&local->sockets.lock); rwlock_init(&local->connecting_sockets.lock); rwlock_init(&local->raw_sockets.lock); local->lto = 150; /* 1500 ms */ local->rw = LLCP_MAX_RW; local->miux = cpu_to_be16(LLCP_MAX_MIUX); local->local_wks = 0x1; /* LLC Link Management */ nfc_llcp_build_gb(local); local->remote_miu = LLCP_DEFAULT_MIU; local->remote_lto = LLCP_DEFAULT_LTO; mutex_init(&local->sdreq_lock); INIT_HLIST_HEAD(&local->pending_sdreqs); timer_setup(&local->sdreq_timer, nfc_llcp_sdreq_timer, 0); INIT_WORK(&local->sdreq_timeout_work, nfc_llcp_sdreq_timeout_work); list_add(&local->list, &llcp_devices); return 0; } void nfc_llcp_unregister_device(struct nfc_dev *dev) { struct nfc_llcp_local *local = nfc_llcp_find_local(dev); if (local == NULL) { pr_debug("No such device\n"); return; } local_cleanup(local); nfc_llcp_local_put(local); } int __init nfc_llcp_init(void) { return nfc_llcp_sock_init(); } void nfc_llcp_exit(void) { nfc_llcp_sock_exit(); }
static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, *version_tlv, version, version_length; u8 *lto_tlv, lto_length; u8 *wks_tlv, wks_length; u8 *miux_tlv, miux_length; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; }
static int nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, version, version_length; u8 lto_length, wks_length, miux_length; u8 *version_tlv = NULL, *lto_tlv = NULL, *wks_tlv = NULL, *miux_tlv = NULL; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); if (!version_tlv) { ret = -ENOMEM; goto out; } gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); if (!lto_tlv) { ret = -ENOMEM; goto out; } gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); if (!wks_tlv) { ret = -ENOMEM; goto out; } gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); if (!miux_tlv) { ret = -ENOMEM; goto out; } gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; }
{'added': [(535, '\tu8 *gb_cur, version, version_length;'), (536, '\tu8 lto_length, wks_length, miux_length;'), (537, '\tu8 *version_tlv = NULL, *lto_tlv = NULL,'), (538, '\t *wks_tlv = NULL, *miux_tlv = NULL;'), (546, '\tif (!version_tlv) {'), (547, '\t\tret = -ENOMEM;'), (548, '\t\tgoto out;'), (549, '\t}'), (553, '\tif (!lto_tlv) {'), (554, '\t\tret = -ENOMEM;'), (555, '\t\tgoto out;'), (556, '\t}'), (561, '\tif (!wks_tlv) {'), (562, '\t\tret = -ENOMEM;'), (563, '\t\tgoto out;'), (564, '\t}'), (569, '\tif (!miux_tlv) {'), (570, '\t\tret = -ENOMEM;'), (571, '\t\tgoto out;'), (572, '\t}')], 'deleted': [(535, '\tu8 *gb_cur, *version_tlv, version, version_length;'), (536, '\tu8 *lto_tlv, lto_length;'), (537, '\tu8 *wks_tlv, wks_length;'), (538, '\tu8 *miux_tlv, miux_length;')]}
20
4
1,185
7,072
https://github.com/torvalds/linux
CVE-2019-12818
['CWE-476']
gd_tga.c
read_image_tga
/** * File: TGA Input * * Read TGA images. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /* Function: gdImageCreateFromTga Creates a gdImage from a TGA file Parameters: infile - Pointer to TGA binary file */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } /* Function: gdImageCreateFromTgaPtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromTgaCtx Creates a gdImage from a gdIOCtx referencing a TGA binary file. Parameters: ctx - Pointer to a gdIOCtx structure */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
/** * File: TGA Input * * Read TGA images. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /* Function: gdImageCreateFromTga Creates a gdImage from a TGA file Parameters: infile - Pointer to TGA binary file */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } /* Function: gdImageCreateFromTgaPtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromTgaCtx Creates a gdImage from a gdIOCtx referencing a TGA binary file. Parameters: ctx - Pointer to a gdIOCtx structure */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; }
int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; }
{'added': [(303, '\t\t\t\tif ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size'), (304, '\t\t\t\t\t\t|| buffer_caret + pixel_block_size > rle_size) {'), (320, '\t\t\t\tif ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size'), (321, '\t\t\t\t\t\t|| buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) {')], 'deleted': [(303, '\t\t\t\tif ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) {'), (319, '\t\t\t\tif ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) {')]}
4
2
232
1,625
https://github.com/libgd/libgd
CVE-2016-6906
['CWE-125']
request_key.c
construct_get_dest_keyring
/* Request a key from userspace * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static void construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
/* Request a key from userspace * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static int construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; int ret; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { bool do_perm_check = true; /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) { do_perm_check = false; break; } } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } /* * Require Write permission on the keyring. This is essential * because the default keyring may be the session keyring, and * joining a keyring only requires Search permission. * * However, this check is skipped for the "requestor keyring" so * that /sbin/request-key can itself use request_key() to add * keys to the original requestor's destination keyring. */ if (dest_keyring && do_perm_check) { ret = key_permission(make_key_ref(dest_keyring, 1), KEY_NEED_WRITE); if (ret) { key_put(dest_keyring); return ret; } } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return 0; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); ret = construct_get_dest_keyring(&dest_keyring); if (ret) goto error; user = key_user_lookup(current_fsuid()); if (!user) { ret = -ENOMEM; goto error_put_dest_keyring; } ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto error_put_dest_keyring; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); error_put_dest_keyring: key_put(dest_keyring); error: kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
static void construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; }
static int construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; int ret; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { bool do_perm_check = true; /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) { do_perm_check = false; break; } } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } /* * Require Write permission on the keyring. This is essential * because the default keyring may be the session keyring, and * joining a keyring only requires Search permission. * * However, this check is skipped for the "requestor keyring" so * that /sbin/request-key can itself use request_key() to add * keys to the original requestor's destination keyring. */ if (dest_keyring && do_perm_check) { ret = key_permission(make_key_ref(dest_keyring, 1), KEY_NEED_WRITE); if (ret) { key_put(dest_keyring); return ret; } } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return 0; }
{'added': [(254, 'static int construct_get_dest_keyring(struct key **_dest_keyring)'), (259, '\tint ret;'), (268, '\t\tbool do_perm_check = true;'), (269, ''), (284, '\t\t\t\tif (dest_keyring) {'), (285, '\t\t\t\t\tdo_perm_check = false;'), (287, '\t\t\t\t}'), (322, ''), (323, '\t\t/*'), (324, '\t\t * Require Write permission on the keyring. This is essential'), (325, '\t\t * because the default keyring may be the session keyring, and'), (326, '\t\t * joining a keyring only requires Search permission.'), (327, '\t\t *'), (328, '\t\t * However, this check is skipped for the "requestor keyring" so'), (329, '\t\t * that /sbin/request-key can itself use request_key() to add'), (330, "\t\t * keys to the original requestor's destination keyring."), (331, '\t\t */'), (332, '\t\tif (dest_keyring && do_perm_check) {'), (333, '\t\t\tret = key_permission(make_key_ref(dest_keyring, 1),'), (334, '\t\t\t\t\t KEY_NEED_WRITE);'), (335, '\t\t\tif (ret) {'), (336, '\t\t\t\tkey_put(dest_keyring);'), (337, '\t\t\t\treturn ret;'), (338, '\t\t\t}'), (339, '\t\t}'), (344, '\treturn 0;'), (470, '\tret = construct_get_dest_keyring(&dest_keyring);'), (471, '\tif (ret)'), (472, '\t\tgoto error;'), (474, '\tuser = key_user_lookup(current_fsuid());'), (475, '\tif (!user) {'), (476, '\t\tret = -ENOMEM;'), (477, '\t\tgoto error_put_dest_keyring;'), (478, '\t}'), (493, '\t\tgoto error_put_dest_keyring;'), (503, 'error_put_dest_keyring:'), (505, 'error:')], 'deleted': [(254, 'static void construct_get_dest_keyring(struct key **_dest_keyring)'), (281, '\t\t\t\tif (dest_keyring)'), (321, '\treturn;'), (447, '\tuser = key_user_lookup(current_fsuid());'), (448, '\tif (!user)'), (449, '\t\treturn ERR_PTR(-ENOMEM);'), (451, '\tconstruct_get_dest_keyring(&dest_keyring);'), (466, '\t\tgoto couldnt_alloc_key;'), (476, 'couldnt_alloc_key:')]}
37
9
474
2,761
https://github.com/torvalds/linux
CVE-2017-17807
['CWE-862']
request_key.c
construct_key_and_link
/* Request a key from userspace * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static void construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
/* Request a key from userspace * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static int construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; int ret; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { bool do_perm_check = true; /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) { do_perm_check = false; break; } } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } /* * Require Write permission on the keyring. This is essential * because the default keyring may be the session keyring, and * joining a keyring only requires Search permission. * * However, this check is skipped for the "requestor keyring" so * that /sbin/request-key can itself use request_key() to add * keys to the original requestor's destination keyring. */ if (dest_keyring && do_perm_check) { ret = key_permission(make_key_ref(dest_keyring, 1), KEY_NEED_WRITE); if (ret) { key_put(dest_keyring); return ret; } } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return 0; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); ret = construct_get_dest_keyring(&dest_keyring); if (ret) goto error; user = key_user_lookup(current_fsuid()); if (!user) { ret = -ENOMEM; goto error_put_dest_keyring; } ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto error_put_dest_keyring; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); error_put_dest_keyring: key_put(dest_keyring); error: kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); }
static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); ret = construct_get_dest_keyring(&dest_keyring); if (ret) goto error; user = key_user_lookup(current_fsuid()); if (!user) { ret = -ENOMEM; goto error_put_dest_keyring; } ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto error_put_dest_keyring; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); error_put_dest_keyring: key_put(dest_keyring); error: kleave(" = %d", ret); return ERR_PTR(ret); }
{'added': [(254, 'static int construct_get_dest_keyring(struct key **_dest_keyring)'), (259, '\tint ret;'), (268, '\t\tbool do_perm_check = true;'), (269, ''), (284, '\t\t\t\tif (dest_keyring) {'), (285, '\t\t\t\t\tdo_perm_check = false;'), (287, '\t\t\t\t}'), (322, ''), (323, '\t\t/*'), (324, '\t\t * Require Write permission on the keyring. This is essential'), (325, '\t\t * because the default keyring may be the session keyring, and'), (326, '\t\t * joining a keyring only requires Search permission.'), (327, '\t\t *'), (328, '\t\t * However, this check is skipped for the "requestor keyring" so'), (329, '\t\t * that /sbin/request-key can itself use request_key() to add'), (330, "\t\t * keys to the original requestor's destination keyring."), (331, '\t\t */'), (332, '\t\tif (dest_keyring && do_perm_check) {'), (333, '\t\t\tret = key_permission(make_key_ref(dest_keyring, 1),'), (334, '\t\t\t\t\t KEY_NEED_WRITE);'), (335, '\t\t\tif (ret) {'), (336, '\t\t\t\tkey_put(dest_keyring);'), (337, '\t\t\t\treturn ret;'), (338, '\t\t\t}'), (339, '\t\t}'), (344, '\treturn 0;'), (470, '\tret = construct_get_dest_keyring(&dest_keyring);'), (471, '\tif (ret)'), (472, '\t\tgoto error;'), (474, '\tuser = key_user_lookup(current_fsuid());'), (475, '\tif (!user) {'), (476, '\t\tret = -ENOMEM;'), (477, '\t\tgoto error_put_dest_keyring;'), (478, '\t}'), (493, '\t\tgoto error_put_dest_keyring;'), (503, 'error_put_dest_keyring:'), (505, 'error:')], 'deleted': [(254, 'static void construct_get_dest_keyring(struct key **_dest_keyring)'), (281, '\t\t\t\tif (dest_keyring)'), (321, '\treturn;'), (447, '\tuser = key_user_lookup(current_fsuid());'), (448, '\tif (!user)'), (449, '\t\treturn ERR_PTR(-ENOMEM);'), (451, '\tconstruct_get_dest_keyring(&dest_keyring);'), (466, '\t\tgoto couldnt_alloc_key;'), (476, 'couldnt_alloc_key:')]}
37
9
474
2,761
https://github.com/torvalds/linux
CVE-2017-17807
['CWE-862']
bson-iter.c
_bson_iter_next_internal
/* * Copyright 2013-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bson/bson-iter.h" #include "bson/bson-config.h" #include "bson/bson-decimal128.h" #include "bson-types.h" #define ITER_TYPE(i) ((bson_type_t) * ((i)->raw + (i)->type)) /* *-------------------------------------------------------------------------- * * bson_iter_init -- * * Initializes @iter to be used to iterate @bson. * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init (bson_iter_t *iter, /* OUT */ const bson_t *bson) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); if (BSON_UNLIKELY (bson->len < 5)) { memset (iter, 0, sizeof *iter); return false; } iter->raw = bson_get_data (bson); iter->len = bson->len; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_from_data -- * * Initializes @iter to be used to iterate @data of length @length * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init_from_data (bson_iter_t *iter, /* OUT */ const uint8_t *data, /* IN */ size_t length) /* IN */ { uint32_t len_le; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } memcpy (&len_le, data, sizeof (len_le)); if (BSON_UNLIKELY ((size_t) BSON_UINT32_FROM_LE (len_le) != length)) { memset (iter, 0, sizeof *iter); return false; } if (BSON_UNLIKELY (data[length - 1])) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = length; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_recurse -- * * Creates a new sub-iter looking at the document or array that @iter * is currently pointing at. * * Returns: * true if successful and @child was initialized. * * Side effects: * @child is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_recurse (const bson_iter_t *iter, /* IN */ bson_iter_t *child) /* OUT */ { const uint8_t *data = NULL; uint32_t len = 0; BSON_ASSERT (iter); BSON_ASSERT (child); if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { bson_iter_document (iter, &len, &data); } else if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { bson_iter_array (iter, &len, &data); } else { return false; } child->raw = data; child->len = len; child->off = 0; child->type = 0; child->key = 0; child->d1 = 0; child->d2 = 0; child->d3 = 0; child->d4 = 0; child->next_off = 4; child->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_find -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_w_len -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_w_len (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key, /* IN */ int keylen) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_w_len (iter, key, keylen); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_case -- * * A case-insensitive version of bson_iter_init_find(). * * Returns: * true if the field was found and @iter is observing that field. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_case (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_case (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_find_w_len -- * * Searches through @iter starting from the current position for a key * matching @key. @keylen indicates the length of @key, or -1 to * determine the length with strlen(). * * Returns: * true if the field @key was found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_w_len (bson_iter_t *iter, /* INOUT */ const char *key, /* IN */ int keylen) /* IN */ { const char *ikey; if (keylen < 0) { keylen = (int) strlen (key); } while (bson_iter_next (iter)) { ikey = bson_iter_key (iter); if ((0 == strncmp (key, ikey, keylen)) && (ikey[keylen] == '\0')) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-sensitive search meaning "KEY" and * "key" would NOT match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); return bson_iter_find_w_len (iter, key, -1); } /* *-------------------------------------------------------------------------- * * bson_iter_find_case -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-insensitive search meaning "KEY" and * "key" would match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_case (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); while (bson_iter_next (iter)) { if (!bson_strcasecmp (key, bson_iter_key (iter))) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find_descendant -- * * Locates a descendant using the "parent.child.key" notation. This * operates similar to bson_iter_find() except that it can recurse * into children documents using the dot notation. * * Returns: * true if the descendant was found and @descendant was initialized. * * Side effects: * @descendant may be initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_find_descendant (bson_iter_t *iter, /* INOUT */ const char *dotkey, /* IN */ bson_iter_t *descendant) /* OUT */ { bson_iter_t tmp; const char *dot; size_t sublen; BSON_ASSERT (iter); BSON_ASSERT (dotkey); BSON_ASSERT (descendant); if ((dot = strchr (dotkey, '.'))) { sublen = dot - dotkey; } else { sublen = strlen (dotkey); } if (bson_iter_find_w_len (iter, dotkey, (int) sublen)) { if (!dot) { *descendant = *iter; return true; } if (BSON_ITER_HOLDS_DOCUMENT (iter) || BSON_ITER_HOLDS_ARRAY (iter)) { if (bson_iter_recurse (iter, &tmp)) { return bson_iter_find_descendant (&tmp, dot + 1, descendant); } } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_key -- * * Retrieves the key of the current field. The resulting key is valid * while @iter is valid. * * Returns: * A string that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_key (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); return bson_iter_key_unsafe (iter); } /* *-------------------------------------------------------------------------- * * bson_iter_type -- * * Retrieves the type of the current field. It may be useful to check * the type using the BSON_ITER_HOLDS_*() macros. * * Returns: * A bson_type_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bson_type_t bson_iter_type (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (iter->raw); BSON_ASSERT (iter->len); return bson_iter_type_unsafe (iter); } /* *-------------------------------------------------------------------------- * * _bson_iter_next_internal -- * * Internal function to advance @iter to the next field and retrieve * the key and BSON type before error-checking. @next_keylen is * the key length of the next field being iterated or 0 if this is * not known. * * Return: * true if an element was decoded, else false. * * Side effects: * @key and @bson_type are set. * * If the return value is false: * - @iter is invalidated: @iter->raw is NULLed * - @unsupported is set to true if the bson type is unsupported * - otherwise if the BSON is corrupt, @iter->err_off is nonzero * - otherwise @bson_type is set to BSON_TYPE_EOD * *-------------------------------------------------------------------------- */ static bool _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; } /* *-------------------------------------------------------------------------- * * bson_iter_next -- * * Advances @iter to the next field of the underlying BSON document. * If all fields have been exhausted, then %false is returned. * * It is a programming error to use @iter after this function has * returned false. * * Returns: * true if the iter was advanced to the next record. * otherwise false and @iter should be considered invalid. * * Side effects: * @iter may be invalidated. * *-------------------------------------------------------------------------- */ bool bson_iter_next (bson_iter_t *iter) /* INOUT */ { uint32_t bson_type; const char *key; bool unsupported; return _bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported); } /* *-------------------------------------------------------------------------- * * bson_iter_binary -- * * Retrieves the BSON_TYPE_BINARY field. The subtype is stored in * @subtype. The length of @binary in bytes is stored in @binary_len. * * @binary should not be modified or freed and is only valid while * @iter's bson_t is valid and unmodified. * * Parameters: * @iter: A bson_iter_t * @subtype: A location for the binary subtype. * @binary_len: A location for the length of @binary. * @binary: A location for a pointer to the binary data. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_binary (const bson_iter_t *iter, /* IN */ bson_subtype_t *subtype, /* OUT */ uint32_t *binary_len, /* OUT */ const uint8_t **binary) /* OUT */ { bson_subtype_t backup; BSON_ASSERT (iter); BSON_ASSERT (!binary || binary_len); if (ITER_TYPE (iter) == BSON_TYPE_BINARY) { if (!subtype) { subtype = &backup; } *subtype = (bson_subtype_t) * (iter->raw + iter->d2); if (binary) { memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len)); *binary_len = BSON_UINT32_FROM_LE (*binary_len); *binary = iter->raw + iter->d3; if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { *binary_len -= sizeof (int32_t); *binary += sizeof (int32_t); } } return; } if (binary) { *binary = NULL; } if (binary_len) { *binary_len = 0; } if (subtype) { *subtype = BSON_SUBTYPE_BINARY; } } /* *-------------------------------------------------------------------------- * * bson_iter_bool -- * * Retrieves the current field of type BSON_TYPE_BOOL. * * Returns: * true or false, dependent on bson document. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { return bson_iter_bool_unsafe (iter); } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_as_bool -- * * If @iter is on a boolean field, returns the boolean. If it is on a * non-boolean field such as int32, int64, or double, it will convert * the value to a boolean. * * Zero is false, and non-zero is true. * * Returns: * true or false, dependent on field type. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_as_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return !(bson_iter_double (iter) == 0.0); case BSON_TYPE_INT64: return !(bson_iter_int64 (iter) == 0); case BSON_TYPE_INT32: return !(bson_iter_int32 (iter) == 0); case BSON_TYPE_UTF8: return true; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: return false; default: return true; } } /* *-------------------------------------------------------------------------- * * bson_iter_double -- * * Retrieves the current field of type BSON_TYPE_DOUBLE. * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { return bson_iter_double_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_double -- * * If @iter is on a field of type BSON_TYPE_DOUBLE, * returns the double. If it is on an integer field * such as int32, int64, or bool, it will convert * the value to a double. * * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_as_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (double) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return bson_iter_double (iter); case BSON_TYPE_INT32: return (double) bson_iter_int32 (iter); case BSON_TYPE_INT64: return (double) bson_iter_int64 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_int32 -- * * Retrieves the value of the field of type BSON_TYPE_INT32. * * Returns: * A 32-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int32_t bson_iter_int32 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { return bson_iter_int32_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_int64 -- * * Retrieves a 64-bit signed integer for the current BSON_TYPE_INT64 * field. * * Returns: * A 64-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_int64 -- * * If @iter is not an int64 field, it will try to convert the value to * an int64. Such field types include: * * - bool * - double * - int32 * * Returns: * An int64_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_as_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (int64_t) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return (int64_t) bson_iter_double (iter); case BSON_TYPE_INT64: return bson_iter_int64 (iter); case BSON_TYPE_INT32: return (int64_t) bson_iter_int32 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_decimal128 -- * * This function retrieves the current field of type *%BSON_TYPE_DECIMAL128. * The result is valid while @iter is valid, and is stored in @dec. * * Returns: * * True on success, false on failure. * * Side Effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_decimal128 (const bson_iter_t *iter, /* IN */ bson_decimal128_t *dec) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { bson_iter_decimal128_unsafe (iter, dec); return true; } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_oid -- * * Retrieves the current field of type %BSON_TYPE_OID. The result is * valid while @iter is valid. * * Returns: * A bson_oid_t that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_oid_t * bson_iter_oid (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { return bson_iter_oid_unsafe (iter); } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_regex -- * * Fetches the current field from the iter which should be of type * BSON_TYPE_REGEX. * * Returns: * Regex from @iter. This should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_regex (const bson_iter_t *iter, /* IN */ const char **options) /* IN */ { const char *ret = NULL; const char *ret_options = NULL; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_REGEX) { ret = (const char *) (iter->raw + iter->d1); ret_options = (const char *) (iter->raw + iter->d2); } if (options) { *options = ret_options; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_utf8 -- * * Retrieves the current field of type %BSON_TYPE_UTF8 as a UTF-8 * encoded string. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the string. * * Returns: * A string that should not be modified or freed. * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ const char * bson_iter_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_UTF8) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dup_utf8 -- * * Copies the current UTF-8 element into a newly allocated string. The * string should be freed using bson_free() when the caller is * finished with it. * * Returns: * A newly allocated char* that should be freed with bson_free(). * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ char * bson_iter_dup_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { uint32_t local_length = 0; const char *str; char *ret = NULL; BSON_ASSERT (iter); if ((str = bson_iter_utf8 (iter, &local_length))) { ret = bson_malloc0 (local_length + 1); memcpy (ret, str, local_length); ret[local_length] = '\0'; } if (length) { *length = local_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_code -- * * Retrieves the current field of type %BSON_TYPE_CODE. The length of * the resulting string is stored in @length. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the code length. * * Returns: * A NUL-terminated string containing the code which should not be * modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_code (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODE) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_codewscope -- * * Similar to bson_iter_code() but with a scope associated encoded as * a BSON document. @scope should not be modified or freed. It is * valid while @iter is valid. * * Parameters: * @iter: A #bson_iter_t. * @length: A location for the length of resulting string. * @scope_len: A location for the length of @scope. * @scope: A location for the scope encoded as BSON. * * Returns: * A NUL-terminated string that should not be modified or freed. * * Side effects: * @length is set to the resulting string length in bytes. * @scope_len is set to the length of @scope in bytes. * @scope is set to the scope documents buffer which can be * turned into a bson document with bson_init_static(). * *-------------------------------------------------------------------------- */ const char * bson_iter_codewscope (const bson_iter_t *iter, /* IN */ uint32_t *length, /* OUT */ uint32_t *scope_len, /* OUT */ const uint8_t **scope) /* OUT */ { uint32_t len; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) { if (length) { memcpy (&len, iter->raw + iter->d2, sizeof (len)); /* The string length was checked > 0 in _bson_iter_next_internal. */ len = BSON_UINT32_FROM_LE (len); BSON_ASSERT (len > 0); *length = len - 1; } memcpy (&len, iter->raw + iter->d4, sizeof (len)); *scope_len = BSON_UINT32_FROM_LE (len); *scope = iter->raw + iter->d4; return (const char *) (iter->raw + iter->d3); } if (length) { *length = 0; } if (scope_len) { *scope_len = 0; } if (scope) { *scope = NULL; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dbpointer -- * * Retrieves a BSON_TYPE_DBPOINTER field. @collection_len will be set * to the length of the collection name. The collection name will be * placed into @collection. The oid will be placed into @oid. * * @collection and @oid should not be modified. * * Parameters: * @iter: A #bson_iter_t. * @collection_len: A location for the length of @collection. * @collection: A location for the collection name. * @oid: A location for the oid. * * Returns: * None. * * Side effects: * @collection_len is set to the length of @collection in bytes * excluding the null byte. * @collection is set to the collection name, including a terminating * null byte. * @oid is initialized with the oid. * *-------------------------------------------------------------------------- */ void bson_iter_dbpointer (const bson_iter_t *iter, /* IN */ uint32_t *collection_len, /* OUT */ const char **collection, /* OUT */ const bson_oid_t **oid) /* OUT */ { BSON_ASSERT (iter); if (collection) { *collection = NULL; } if (oid) { *oid = NULL; } if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) { if (collection_len) { memcpy ( collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); *collection_len = BSON_UINT32_FROM_LE (*collection_len); if ((*collection_len) > 0) { (*collection_len)--; } } if (collection) { *collection = (const char *) (iter->raw + iter->d2); } if (oid) { *oid = (const bson_oid_t *) (iter->raw + iter->d3); } } } /* *-------------------------------------------------------------------------- * * bson_iter_symbol -- * * Retrieves the symbol of the current field of type BSON_TYPE_SYMBOL. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the symbol. * * Returns: * A string containing the symbol as UTF-8. The value should not be * modified or freed. * * Side effects: * @length is set to the resulting strings length in bytes, * excluding the null byte. * *-------------------------------------------------------------------------- */ const char * bson_iter_symbol (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { const char *ret = NULL; uint32_t ret_length = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_SYMBOL) { ret = (const char *) (iter->raw + iter->d2); ret_length = bson_iter_utf8_len_unsafe (iter); } if (length) { *length = ret_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_date_time -- * * Fetches the number of milliseconds elapsed since the UNIX epoch. * This value can be negative as times before 1970 are valid. * * Returns: * A signed 64-bit integer containing the number of milliseconds. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_date_time (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_time_t -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME as a * time_t. * * Returns: * A #time_t of the number of seconds since UNIX epoch in UTC. * * Side effects: * None. * *-------------------------------------------------------------------------- */ time_t bson_iter_time_t (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_time_t_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_timestamp -- * * Fetches the current field if it is a BSON_TYPE_TIMESTAMP. * * Parameters: * @iter: A #bson_iter_t. * @timestamp: a location for the timestamp. * @increment: A location for the increment. * * Returns: * None. * * Side effects: * @timestamp is initialized. * @increment is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timestamp (const bson_iter_t *iter, /* IN */ uint32_t *timestamp, /* OUT */ uint32_t *increment) /* OUT */ { uint64_t encoded; uint32_t ret_timestamp = 0; uint32_t ret_increment = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { memcpy (&encoded, iter->raw + iter->d1, sizeof (encoded)); encoded = BSON_UINT64_FROM_LE (encoded); ret_timestamp = (encoded >> 32) & 0xFFFFFFFF; ret_increment = encoded & 0xFFFFFFFF; } if (timestamp) { *timestamp = ret_timestamp; } if (increment) { *increment = ret_increment; } } /* *-------------------------------------------------------------------------- * * bson_iter_timeval -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME and stores * it into the struct timeval provided. tv->tv_sec is set to the * number of seconds since the UNIX epoch in UTC. * * Since BSON_TYPE_DATE_TIME does not support fractions of a second, * tv->tv_usec will always be set to zero. * * Returns: * None. * * Side effects: * @tv is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timeval (const bson_iter_t *iter, /* IN */ struct timeval *tv) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { bson_iter_timeval_unsafe (iter, tv); return; } memset (tv, 0, sizeof *tv); } /** * bson_iter_document: * @iter: a bson_iter_t. * @document_len: A location for the document length. * @document: A location for a pointer to the document buffer. * */ /* *-------------------------------------------------------------------------- * * bson_iter_document -- * * Retrieves the data to the document BSON structure and stores the * length of the document buffer in @document_len and the document * buffer in @document. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_document(iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the bson_t structure as no data can be * modified in the process of its use (as it is static/const). * * Returns: * None. * * Side effects: * @document_len is initialized. * @document is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_document (const bson_iter_t *iter, /* IN */ uint32_t *document_len, /* OUT */ const uint8_t **document) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (document_len); BSON_ASSERT (document); *document = NULL; *document_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len)); *document_len = BSON_UINT32_FROM_LE (*document_len); *document = (iter->raw + iter->d1); } } /** * bson_iter_array: * @iter: a #bson_iter_t. * @array_len: A location for the array length. * @array: A location for a pointer to the array buffer. */ /* *-------------------------------------------------------------------------- * * bson_iter_array -- * * Retrieves the data to the array BSON structure and stores the * length of the array buffer in @array_len and the array buffer in * @array. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_array (iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the #bson_t structure as no data can be * modified in the process of its use. * * Returns: * None. * * Side effects: * @array_len is initialized. * @array is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_array (const bson_iter_t *iter, /* IN */ uint32_t *array_len, /* OUT */ const uint8_t **array) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (array_len); BSON_ASSERT (array); *array = NULL; *array_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { memcpy (array_len, (iter->raw + iter->d1), sizeof (*array_len)); *array_len = BSON_UINT32_FROM_LE (*array_len); *array = (iter->raw + iter->d1); } } #define VISIT_FIELD(name) visitor->visit_##name && visitor->visit_##name #define VISIT_AFTER VISIT_FIELD (after) #define VISIT_BEFORE VISIT_FIELD (before) #define VISIT_CORRUPT \ if (visitor->visit_corrupt) \ visitor->visit_corrupt #define VISIT_DOUBLE VISIT_FIELD (double) #define VISIT_UTF8 VISIT_FIELD (utf8) #define VISIT_DOCUMENT VISIT_FIELD (document) #define VISIT_ARRAY VISIT_FIELD (array) #define VISIT_BINARY VISIT_FIELD (binary) #define VISIT_UNDEFINED VISIT_FIELD (undefined) #define VISIT_OID VISIT_FIELD (oid) #define VISIT_BOOL VISIT_FIELD (bool) #define VISIT_DATE_TIME VISIT_FIELD (date_time) #define VISIT_NULL VISIT_FIELD (null) #define VISIT_REGEX VISIT_FIELD (regex) #define VISIT_DBPOINTER VISIT_FIELD (dbpointer) #define VISIT_CODE VISIT_FIELD (code) #define VISIT_SYMBOL VISIT_FIELD (symbol) #define VISIT_CODEWSCOPE VISIT_FIELD (codewscope) #define VISIT_INT32 VISIT_FIELD (int32) #define VISIT_TIMESTAMP VISIT_FIELD (timestamp) #define VISIT_INT64 VISIT_FIELD (int64) #define VISIT_DECIMAL128 VISIT_FIELD (decimal128) #define VISIT_MAXKEY VISIT_FIELD (maxkey) #define VISIT_MINKEY VISIT_FIELD (minkey) bool bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ const bson_visitor_t *visitor, /* IN */ void *data) /* IN */ { uint32_t bson_type; const char *key; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (visitor); while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { if (*key && !bson_utf8_validate (key, strlen (key), false)) { iter->err_off = iter->off; break; } if (VISIT_BEFORE (iter, key, data)) { return true; } switch (bson_type) { case BSON_TYPE_DOUBLE: if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { return true; } break; case BSON_TYPE_UTF8: { uint32_t utf8_len; const char *utf8; utf8 = bson_iter_utf8 (iter, &utf8_len); if (!bson_utf8_validate (utf8, utf8_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { return true; } } break; case BSON_TYPE_DOCUMENT: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_document (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_DOCUMENT (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_ARRAY: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_array (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_ARRAY (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_BINARY: { const uint8_t *binary = NULL; bson_subtype_t subtype = BSON_SUBTYPE_BINARY; uint32_t binary_len = 0; bson_iter_binary (iter, &subtype, &binary_len, &binary); if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { return true; } } break; case BSON_TYPE_UNDEFINED: if (VISIT_UNDEFINED (iter, key, data)) { return true; } break; case BSON_TYPE_OID: if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { return true; } break; case BSON_TYPE_BOOL: if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { return true; } break; case BSON_TYPE_DATE_TIME: if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { return true; } break; case BSON_TYPE_NULL: if (VISIT_NULL (iter, key, data)) { return true; } break; case BSON_TYPE_REGEX: { const char *regex = NULL; const char *options = NULL; regex = bson_iter_regex (iter, &options); if (!bson_utf8_validate (regex, strlen (regex), true)) { iter->err_off = iter->off; return true; } if (VISIT_REGEX (iter, key, regex, options, data)) { return true; } } break; case BSON_TYPE_DBPOINTER: { uint32_t collection_len = 0; const char *collection = NULL; const bson_oid_t *oid = NULL; bson_iter_dbpointer (iter, &collection_len, &collection, &oid); if (!bson_utf8_validate (collection, collection_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_DBPOINTER ( iter, key, collection_len, collection, oid, data)) { return true; } } break; case BSON_TYPE_CODE: { uint32_t code_len; const char *code; code = bson_iter_code (iter, &code_len); if (!bson_utf8_validate (code, code_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_CODE (iter, key, code_len, code, data)) { return true; } } break; case BSON_TYPE_SYMBOL: { uint32_t symbol_len; const char *symbol; symbol = bson_iter_symbol (iter, &symbol_len); if (!bson_utf8_validate (symbol, symbol_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { return true; } } break; case BSON_TYPE_CODEWSCOPE: { uint32_t length = 0; const char *code; const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); if (!bson_utf8_validate (code, length, true)) { iter->err_off = iter->off; return true; } if (bson_init_static (&b, docbuf, doclen) && VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { return true; } } break; case BSON_TYPE_INT32: if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { return true; } break; case BSON_TYPE_TIMESTAMP: { uint32_t timestamp; uint32_t increment; bson_iter_timestamp (iter, &timestamp, &increment); if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { return true; } } break; case BSON_TYPE_INT64: if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { return true; } break; case BSON_TYPE_DECIMAL128: { bson_decimal128_t dec; bson_iter_decimal128 (iter, &dec); if (VISIT_DECIMAL128 (iter, key, &dec, data)) { return true; } } break; case BSON_TYPE_MAXKEY: if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_MINKEY: if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_EOD: default: break; } if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { return true; } } if (iter->err_off) { if (unsupported && visitor->visit_unsupported_type && bson_utf8_validate (key, strlen (key), false)) { visitor->visit_unsupported_type (iter, key, bson_type, data); return false; } VISIT_CORRUPT (iter, data); } #undef VISIT_FIELD return false; } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_bool -- * * Overwrites the current BSON_TYPE_BOOLEAN field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_bool (bson_iter_t *iter, /* IN */ bool value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { memcpy ((void *) (iter->raw + iter->d1), &value, 1); } } void bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { memcpy ( (void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); } } void bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment) { uint64_t value; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { value = ((((uint64_t) timestamp) << 32U) | ((uint64_t) increment)); value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } void bson_iter_overwrite_date_time (bson_iter_t *iter, int64_t value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int32 -- * * Overwrites the current BSON_TYPE_INT32 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int32 (bson_iter_t *iter, /* IN */ int32_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT32_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int64 -- * * Overwrites the current BSON_TYPE_INT64 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int64 (bson_iter_t *iter, /* IN */ int64_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT64_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_double -- * * Overwrites the current BSON_TYPE_DOUBLE field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_double (bson_iter_t *iter, /* IN */ double value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { value = BSON_DOUBLE_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_decimal128 -- * * Overwrites the current BSON_TYPE_DECIMAL128 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_decimal128 (bson_iter_t *iter, /* IN */ bson_decimal128_t *value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN uint64_t data[2]; data[0] = BSON_UINT64_TO_LE (value->low); data[1] = BSON_UINT64_TO_LE (value->high); memcpy ((void *) (iter->raw + iter->d1), data, sizeof (data)); #else memcpy ((void *) (iter->raw + iter->d1), value, sizeof (*value)); #endif } } /* *-------------------------------------------------------------------------- * * bson_iter_value -- * * Retrieves a bson_value_t containing the boxed value of the current * element. The result of this function valid until the state of * iter has been changed (through the use of bson_iter_next()). * * Returns: * A bson_value_t that should not be modified or freed. If you need * to hold on to the value, use bson_value_copy(). * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_value_t * bson_iter_value (bson_iter_t *iter) /* IN */ { bson_value_t *value; BSON_ASSERT (iter); value = &iter->value; value->value_type = ITER_TYPE (iter); switch (value->value_type) { case BSON_TYPE_DOUBLE: value->value.v_double = bson_iter_double (iter); break; case BSON_TYPE_UTF8: value->value.v_utf8.str = (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: bson_iter_document (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_ARRAY: bson_iter_array (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_BINARY: bson_iter_binary (iter, &value->value.v_binary.subtype, &value->value.v_binary.data_len, (const uint8_t **) &value->value.v_binary.data); break; case BSON_TYPE_OID: bson_oid_copy (bson_iter_oid (iter), &value->value.v_oid); break; case BSON_TYPE_BOOL: value->value.v_bool = bson_iter_bool (iter); break; case BSON_TYPE_DATE_TIME: value->value.v_datetime = bson_iter_date_time (iter); break; case BSON_TYPE_REGEX: value->value.v_regex.regex = (char *) bson_iter_regex ( iter, (const char **) &value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: { const bson_oid_t *oid; bson_iter_dbpointer (iter, &value->value.v_dbpointer.collection_len, (const char **) &value->value.v_dbpointer.collection, &oid); bson_oid_copy (oid, &value->value.v_dbpointer.oid); break; } case BSON_TYPE_CODE: value->value.v_code.code = (char *) bson_iter_code (iter, &value->value.v_code.code_len); break; case BSON_TYPE_SYMBOL: value->value.v_symbol.symbol = (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: value->value.v_codewscope.code = (char *) bson_iter_codewscope ( iter, &value->value.v_codewscope.code_len, &value->value.v_codewscope.scope_len, (const uint8_t **) &value->value.v_codewscope.scope_data); break; case BSON_TYPE_INT32: value->value.v_int32 = bson_iter_int32 (iter); break; case BSON_TYPE_TIMESTAMP: bson_iter_timestamp (iter, &value->value.v_timestamp.timestamp, &value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: value->value.v_int64 = bson_iter_int64 (iter); break; case BSON_TYPE_DECIMAL128: bson_iter_decimal128 (iter, &(value->value.v_decimal128)); break; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: break; case BSON_TYPE_EOD: default: return NULL; } return value; } uint32_t bson_iter_key_len (const bson_iter_t *iter) { /* * f i e l d n a m e \0 _ * ^ ^ * | | * iter->key iter->d1 * */ BSON_ASSERT (iter->d1 > iter->key); return iter->d1 - iter->key - 1; } bool bson_iter_init_from_data_at_offset (bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen) { const char *key; uint32_t bson_type; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = (uint32_t) length; iter->off = 0; iter->type = 0; iter->key = 0; iter->next_off = offset; iter->err_off = 0; if (!_bson_iter_next_internal ( iter, keylen, &key, &bson_type, &unsupported)) { memset (iter, 0, sizeof *iter); return false; } return true; } uint32_t bson_iter_offset (bson_iter_t *iter) { return iter->off; }
/* * Copyright 2013-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bson/bson-iter.h" #include "bson/bson-config.h" #include "bson/bson-decimal128.h" #include "bson-types.h" #define ITER_TYPE(i) ((bson_type_t) * ((i)->raw + (i)->type)) /* *-------------------------------------------------------------------------- * * bson_iter_init -- * * Initializes @iter to be used to iterate @bson. * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init (bson_iter_t *iter, /* OUT */ const bson_t *bson) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); if (BSON_UNLIKELY (bson->len < 5)) { memset (iter, 0, sizeof *iter); return false; } iter->raw = bson_get_data (bson); iter->len = bson->len; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_from_data -- * * Initializes @iter to be used to iterate @data of length @length * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init_from_data (bson_iter_t *iter, /* OUT */ const uint8_t *data, /* IN */ size_t length) /* IN */ { uint32_t len_le; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } memcpy (&len_le, data, sizeof (len_le)); if (BSON_UNLIKELY ((size_t) BSON_UINT32_FROM_LE (len_le) != length)) { memset (iter, 0, sizeof *iter); return false; } if (BSON_UNLIKELY (data[length - 1])) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = length; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_recurse -- * * Creates a new sub-iter looking at the document or array that @iter * is currently pointing at. * * Returns: * true if successful and @child was initialized. * * Side effects: * @child is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_recurse (const bson_iter_t *iter, /* IN */ bson_iter_t *child) /* OUT */ { const uint8_t *data = NULL; uint32_t len = 0; BSON_ASSERT (iter); BSON_ASSERT (child); if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { bson_iter_document (iter, &len, &data); } else if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { bson_iter_array (iter, &len, &data); } else { return false; } child->raw = data; child->len = len; child->off = 0; child->type = 0; child->key = 0; child->d1 = 0; child->d2 = 0; child->d3 = 0; child->d4 = 0; child->next_off = 4; child->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_find -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_w_len -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_w_len (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key, /* IN */ int keylen) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_w_len (iter, key, keylen); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_case -- * * A case-insensitive version of bson_iter_init_find(). * * Returns: * true if the field was found and @iter is observing that field. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_case (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_case (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_find_w_len -- * * Searches through @iter starting from the current position for a key * matching @key. @keylen indicates the length of @key, or -1 to * determine the length with strlen(). * * Returns: * true if the field @key was found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_w_len (bson_iter_t *iter, /* INOUT */ const char *key, /* IN */ int keylen) /* IN */ { const char *ikey; if (keylen < 0) { keylen = (int) strlen (key); } while (bson_iter_next (iter)) { ikey = bson_iter_key (iter); if ((0 == strncmp (key, ikey, keylen)) && (ikey[keylen] == '\0')) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-sensitive search meaning "KEY" and * "key" would NOT match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); return bson_iter_find_w_len (iter, key, -1); } /* *-------------------------------------------------------------------------- * * bson_iter_find_case -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-insensitive search meaning "KEY" and * "key" would match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_case (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); while (bson_iter_next (iter)) { if (!bson_strcasecmp (key, bson_iter_key (iter))) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find_descendant -- * * Locates a descendant using the "parent.child.key" notation. This * operates similar to bson_iter_find() except that it can recurse * into children documents using the dot notation. * * Returns: * true if the descendant was found and @descendant was initialized. * * Side effects: * @descendant may be initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_find_descendant (bson_iter_t *iter, /* INOUT */ const char *dotkey, /* IN */ bson_iter_t *descendant) /* OUT */ { bson_iter_t tmp; const char *dot; size_t sublen; BSON_ASSERT (iter); BSON_ASSERT (dotkey); BSON_ASSERT (descendant); if ((dot = strchr (dotkey, '.'))) { sublen = dot - dotkey; } else { sublen = strlen (dotkey); } if (bson_iter_find_w_len (iter, dotkey, (int) sublen)) { if (!dot) { *descendant = *iter; return true; } if (BSON_ITER_HOLDS_DOCUMENT (iter) || BSON_ITER_HOLDS_ARRAY (iter)) { if (bson_iter_recurse (iter, &tmp)) { return bson_iter_find_descendant (&tmp, dot + 1, descendant); } } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_key -- * * Retrieves the key of the current field. The resulting key is valid * while @iter is valid. * * Returns: * A string that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_key (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); return bson_iter_key_unsafe (iter); } /* *-------------------------------------------------------------------------- * * bson_iter_type -- * * Retrieves the type of the current field. It may be useful to check * the type using the BSON_ITER_HOLDS_*() macros. * * Returns: * A bson_type_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bson_type_t bson_iter_type (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (iter->raw); BSON_ASSERT (iter->len); return bson_iter_type_unsafe (iter); } /* *-------------------------------------------------------------------------- * * _bson_iter_next_internal -- * * Internal function to advance @iter to the next field and retrieve * the key and BSON type before error-checking. @next_keylen is * the key length of the next field being iterated or 0 if this is * not known. * * Return: * true if an element was decoded, else false. * * Side effects: * @key and @bson_type are set. * * If the return value is false: * - @iter is invalidated: @iter->raw is NULLed * - @unsupported is set to true if the bson type is unsupported * - otherwise if the BSON is corrupt, @iter->err_off is nonzero * - otherwise @bson_type is set to BSON_TYPE_EOD * *-------------------------------------------------------------------------- */ static bool _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o - 4)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; } /* *-------------------------------------------------------------------------- * * bson_iter_next -- * * Advances @iter to the next field of the underlying BSON document. * If all fields have been exhausted, then %false is returned. * * It is a programming error to use @iter after this function has * returned false. * * Returns: * true if the iter was advanced to the next record. * otherwise false and @iter should be considered invalid. * * Side effects: * @iter may be invalidated. * *-------------------------------------------------------------------------- */ bool bson_iter_next (bson_iter_t *iter) /* INOUT */ { uint32_t bson_type; const char *key; bool unsupported; return _bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported); } /* *-------------------------------------------------------------------------- * * bson_iter_binary -- * * Retrieves the BSON_TYPE_BINARY field. The subtype is stored in * @subtype. The length of @binary in bytes is stored in @binary_len. * * @binary should not be modified or freed and is only valid while * @iter's bson_t is valid and unmodified. * * Parameters: * @iter: A bson_iter_t * @subtype: A location for the binary subtype. * @binary_len: A location for the length of @binary. * @binary: A location for a pointer to the binary data. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_binary (const bson_iter_t *iter, /* IN */ bson_subtype_t *subtype, /* OUT */ uint32_t *binary_len, /* OUT */ const uint8_t **binary) /* OUT */ { bson_subtype_t backup; BSON_ASSERT (iter); BSON_ASSERT (!binary || binary_len); if (ITER_TYPE (iter) == BSON_TYPE_BINARY) { if (!subtype) { subtype = &backup; } *subtype = (bson_subtype_t) * (iter->raw + iter->d2); if (binary) { memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len)); *binary_len = BSON_UINT32_FROM_LE (*binary_len); *binary = iter->raw + iter->d3; if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { *binary_len -= sizeof (int32_t); *binary += sizeof (int32_t); } } return; } if (binary) { *binary = NULL; } if (binary_len) { *binary_len = 0; } if (subtype) { *subtype = BSON_SUBTYPE_BINARY; } } /* *-------------------------------------------------------------------------- * * bson_iter_bool -- * * Retrieves the current field of type BSON_TYPE_BOOL. * * Returns: * true or false, dependent on bson document. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { return bson_iter_bool_unsafe (iter); } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_as_bool -- * * If @iter is on a boolean field, returns the boolean. If it is on a * non-boolean field such as int32, int64, or double, it will convert * the value to a boolean. * * Zero is false, and non-zero is true. * * Returns: * true or false, dependent on field type. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_as_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return !(bson_iter_double (iter) == 0.0); case BSON_TYPE_INT64: return !(bson_iter_int64 (iter) == 0); case BSON_TYPE_INT32: return !(bson_iter_int32 (iter) == 0); case BSON_TYPE_UTF8: return true; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: return false; default: return true; } } /* *-------------------------------------------------------------------------- * * bson_iter_double -- * * Retrieves the current field of type BSON_TYPE_DOUBLE. * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { return bson_iter_double_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_double -- * * If @iter is on a field of type BSON_TYPE_DOUBLE, * returns the double. If it is on an integer field * such as int32, int64, or bool, it will convert * the value to a double. * * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_as_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (double) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return bson_iter_double (iter); case BSON_TYPE_INT32: return (double) bson_iter_int32 (iter); case BSON_TYPE_INT64: return (double) bson_iter_int64 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_int32 -- * * Retrieves the value of the field of type BSON_TYPE_INT32. * * Returns: * A 32-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int32_t bson_iter_int32 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { return bson_iter_int32_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_int64 -- * * Retrieves a 64-bit signed integer for the current BSON_TYPE_INT64 * field. * * Returns: * A 64-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_int64 -- * * If @iter is not an int64 field, it will try to convert the value to * an int64. Such field types include: * * - bool * - double * - int32 * * Returns: * An int64_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_as_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (int64_t) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return (int64_t) bson_iter_double (iter); case BSON_TYPE_INT64: return bson_iter_int64 (iter); case BSON_TYPE_INT32: return (int64_t) bson_iter_int32 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_decimal128 -- * * This function retrieves the current field of type *%BSON_TYPE_DECIMAL128. * The result is valid while @iter is valid, and is stored in @dec. * * Returns: * * True on success, false on failure. * * Side Effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_decimal128 (const bson_iter_t *iter, /* IN */ bson_decimal128_t *dec) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { bson_iter_decimal128_unsafe (iter, dec); return true; } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_oid -- * * Retrieves the current field of type %BSON_TYPE_OID. The result is * valid while @iter is valid. * * Returns: * A bson_oid_t that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_oid_t * bson_iter_oid (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { return bson_iter_oid_unsafe (iter); } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_regex -- * * Fetches the current field from the iter which should be of type * BSON_TYPE_REGEX. * * Returns: * Regex from @iter. This should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_regex (const bson_iter_t *iter, /* IN */ const char **options) /* IN */ { const char *ret = NULL; const char *ret_options = NULL; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_REGEX) { ret = (const char *) (iter->raw + iter->d1); ret_options = (const char *) (iter->raw + iter->d2); } if (options) { *options = ret_options; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_utf8 -- * * Retrieves the current field of type %BSON_TYPE_UTF8 as a UTF-8 * encoded string. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the string. * * Returns: * A string that should not be modified or freed. * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ const char * bson_iter_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_UTF8) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dup_utf8 -- * * Copies the current UTF-8 element into a newly allocated string. The * string should be freed using bson_free() when the caller is * finished with it. * * Returns: * A newly allocated char* that should be freed with bson_free(). * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ char * bson_iter_dup_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { uint32_t local_length = 0; const char *str; char *ret = NULL; BSON_ASSERT (iter); if ((str = bson_iter_utf8 (iter, &local_length))) { ret = bson_malloc0 (local_length + 1); memcpy (ret, str, local_length); ret[local_length] = '\0'; } if (length) { *length = local_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_code -- * * Retrieves the current field of type %BSON_TYPE_CODE. The length of * the resulting string is stored in @length. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the code length. * * Returns: * A NUL-terminated string containing the code which should not be * modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_code (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODE) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_codewscope -- * * Similar to bson_iter_code() but with a scope associated encoded as * a BSON document. @scope should not be modified or freed. It is * valid while @iter is valid. * * Parameters: * @iter: A #bson_iter_t. * @length: A location for the length of resulting string. * @scope_len: A location for the length of @scope. * @scope: A location for the scope encoded as BSON. * * Returns: * A NUL-terminated string that should not be modified or freed. * * Side effects: * @length is set to the resulting string length in bytes. * @scope_len is set to the length of @scope in bytes. * @scope is set to the scope documents buffer which can be * turned into a bson document with bson_init_static(). * *-------------------------------------------------------------------------- */ const char * bson_iter_codewscope (const bson_iter_t *iter, /* IN */ uint32_t *length, /* OUT */ uint32_t *scope_len, /* OUT */ const uint8_t **scope) /* OUT */ { uint32_t len; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) { if (length) { memcpy (&len, iter->raw + iter->d2, sizeof (len)); /* The string length was checked > 0 in _bson_iter_next_internal. */ len = BSON_UINT32_FROM_LE (len); BSON_ASSERT (len > 0); *length = len - 1; } memcpy (&len, iter->raw + iter->d4, sizeof (len)); *scope_len = BSON_UINT32_FROM_LE (len); *scope = iter->raw + iter->d4; return (const char *) (iter->raw + iter->d3); } if (length) { *length = 0; } if (scope_len) { *scope_len = 0; } if (scope) { *scope = NULL; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dbpointer -- * * Retrieves a BSON_TYPE_DBPOINTER field. @collection_len will be set * to the length of the collection name. The collection name will be * placed into @collection. The oid will be placed into @oid. * * @collection and @oid should not be modified. * * Parameters: * @iter: A #bson_iter_t. * @collection_len: A location for the length of @collection. * @collection: A location for the collection name. * @oid: A location for the oid. * * Returns: * None. * * Side effects: * @collection_len is set to the length of @collection in bytes * excluding the null byte. * @collection is set to the collection name, including a terminating * null byte. * @oid is initialized with the oid. * *-------------------------------------------------------------------------- */ void bson_iter_dbpointer (const bson_iter_t *iter, /* IN */ uint32_t *collection_len, /* OUT */ const char **collection, /* OUT */ const bson_oid_t **oid) /* OUT */ { BSON_ASSERT (iter); if (collection) { *collection = NULL; } if (oid) { *oid = NULL; } if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) { if (collection_len) { memcpy ( collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); *collection_len = BSON_UINT32_FROM_LE (*collection_len); if ((*collection_len) > 0) { (*collection_len)--; } } if (collection) { *collection = (const char *) (iter->raw + iter->d2); } if (oid) { *oid = (const bson_oid_t *) (iter->raw + iter->d3); } } } /* *-------------------------------------------------------------------------- * * bson_iter_symbol -- * * Retrieves the symbol of the current field of type BSON_TYPE_SYMBOL. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the symbol. * * Returns: * A string containing the symbol as UTF-8. The value should not be * modified or freed. * * Side effects: * @length is set to the resulting strings length in bytes, * excluding the null byte. * *-------------------------------------------------------------------------- */ const char * bson_iter_symbol (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { const char *ret = NULL; uint32_t ret_length = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_SYMBOL) { ret = (const char *) (iter->raw + iter->d2); ret_length = bson_iter_utf8_len_unsafe (iter); } if (length) { *length = ret_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_date_time -- * * Fetches the number of milliseconds elapsed since the UNIX epoch. * This value can be negative as times before 1970 are valid. * * Returns: * A signed 64-bit integer containing the number of milliseconds. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_date_time (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_time_t -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME as a * time_t. * * Returns: * A #time_t of the number of seconds since UNIX epoch in UTC. * * Side effects: * None. * *-------------------------------------------------------------------------- */ time_t bson_iter_time_t (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_time_t_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_timestamp -- * * Fetches the current field if it is a BSON_TYPE_TIMESTAMP. * * Parameters: * @iter: A #bson_iter_t. * @timestamp: a location for the timestamp. * @increment: A location for the increment. * * Returns: * None. * * Side effects: * @timestamp is initialized. * @increment is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timestamp (const bson_iter_t *iter, /* IN */ uint32_t *timestamp, /* OUT */ uint32_t *increment) /* OUT */ { uint64_t encoded; uint32_t ret_timestamp = 0; uint32_t ret_increment = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { memcpy (&encoded, iter->raw + iter->d1, sizeof (encoded)); encoded = BSON_UINT64_FROM_LE (encoded); ret_timestamp = (encoded >> 32) & 0xFFFFFFFF; ret_increment = encoded & 0xFFFFFFFF; } if (timestamp) { *timestamp = ret_timestamp; } if (increment) { *increment = ret_increment; } } /* *-------------------------------------------------------------------------- * * bson_iter_timeval -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME and stores * it into the struct timeval provided. tv->tv_sec is set to the * number of seconds since the UNIX epoch in UTC. * * Since BSON_TYPE_DATE_TIME does not support fractions of a second, * tv->tv_usec will always be set to zero. * * Returns: * None. * * Side effects: * @tv is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timeval (const bson_iter_t *iter, /* IN */ struct timeval *tv) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { bson_iter_timeval_unsafe (iter, tv); return; } memset (tv, 0, sizeof *tv); } /** * bson_iter_document: * @iter: a bson_iter_t. * @document_len: A location for the document length. * @document: A location for a pointer to the document buffer. * */ /* *-------------------------------------------------------------------------- * * bson_iter_document -- * * Retrieves the data to the document BSON structure and stores the * length of the document buffer in @document_len and the document * buffer in @document. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_document(iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the bson_t structure as no data can be * modified in the process of its use (as it is static/const). * * Returns: * None. * * Side effects: * @document_len is initialized. * @document is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_document (const bson_iter_t *iter, /* IN */ uint32_t *document_len, /* OUT */ const uint8_t **document) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (document_len); BSON_ASSERT (document); *document = NULL; *document_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len)); *document_len = BSON_UINT32_FROM_LE (*document_len); *document = (iter->raw + iter->d1); } } /** * bson_iter_array: * @iter: a #bson_iter_t. * @array_len: A location for the array length. * @array: A location for a pointer to the array buffer. */ /* *-------------------------------------------------------------------------- * * bson_iter_array -- * * Retrieves the data to the array BSON structure and stores the * length of the array buffer in @array_len and the array buffer in * @array. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_array (iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the #bson_t structure as no data can be * modified in the process of its use. * * Returns: * None. * * Side effects: * @array_len is initialized. * @array is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_array (const bson_iter_t *iter, /* IN */ uint32_t *array_len, /* OUT */ const uint8_t **array) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (array_len); BSON_ASSERT (array); *array = NULL; *array_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { memcpy (array_len, (iter->raw + iter->d1), sizeof (*array_len)); *array_len = BSON_UINT32_FROM_LE (*array_len); *array = (iter->raw + iter->d1); } } #define VISIT_FIELD(name) visitor->visit_##name && visitor->visit_##name #define VISIT_AFTER VISIT_FIELD (after) #define VISIT_BEFORE VISIT_FIELD (before) #define VISIT_CORRUPT \ if (visitor->visit_corrupt) \ visitor->visit_corrupt #define VISIT_DOUBLE VISIT_FIELD (double) #define VISIT_UTF8 VISIT_FIELD (utf8) #define VISIT_DOCUMENT VISIT_FIELD (document) #define VISIT_ARRAY VISIT_FIELD (array) #define VISIT_BINARY VISIT_FIELD (binary) #define VISIT_UNDEFINED VISIT_FIELD (undefined) #define VISIT_OID VISIT_FIELD (oid) #define VISIT_BOOL VISIT_FIELD (bool) #define VISIT_DATE_TIME VISIT_FIELD (date_time) #define VISIT_NULL VISIT_FIELD (null) #define VISIT_REGEX VISIT_FIELD (regex) #define VISIT_DBPOINTER VISIT_FIELD (dbpointer) #define VISIT_CODE VISIT_FIELD (code) #define VISIT_SYMBOL VISIT_FIELD (symbol) #define VISIT_CODEWSCOPE VISIT_FIELD (codewscope) #define VISIT_INT32 VISIT_FIELD (int32) #define VISIT_TIMESTAMP VISIT_FIELD (timestamp) #define VISIT_INT64 VISIT_FIELD (int64) #define VISIT_DECIMAL128 VISIT_FIELD (decimal128) #define VISIT_MAXKEY VISIT_FIELD (maxkey) #define VISIT_MINKEY VISIT_FIELD (minkey) bool bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ const bson_visitor_t *visitor, /* IN */ void *data) /* IN */ { uint32_t bson_type; const char *key; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (visitor); while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { if (*key && !bson_utf8_validate (key, strlen (key), false)) { iter->err_off = iter->off; break; } if (VISIT_BEFORE (iter, key, data)) { return true; } switch (bson_type) { case BSON_TYPE_DOUBLE: if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { return true; } break; case BSON_TYPE_UTF8: { uint32_t utf8_len; const char *utf8; utf8 = bson_iter_utf8 (iter, &utf8_len); if (!bson_utf8_validate (utf8, utf8_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { return true; } } break; case BSON_TYPE_DOCUMENT: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_document (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_DOCUMENT (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_ARRAY: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_array (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_ARRAY (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_BINARY: { const uint8_t *binary = NULL; bson_subtype_t subtype = BSON_SUBTYPE_BINARY; uint32_t binary_len = 0; bson_iter_binary (iter, &subtype, &binary_len, &binary); if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { return true; } } break; case BSON_TYPE_UNDEFINED: if (VISIT_UNDEFINED (iter, key, data)) { return true; } break; case BSON_TYPE_OID: if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { return true; } break; case BSON_TYPE_BOOL: if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { return true; } break; case BSON_TYPE_DATE_TIME: if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { return true; } break; case BSON_TYPE_NULL: if (VISIT_NULL (iter, key, data)) { return true; } break; case BSON_TYPE_REGEX: { const char *regex = NULL; const char *options = NULL; regex = bson_iter_regex (iter, &options); if (!bson_utf8_validate (regex, strlen (regex), true)) { iter->err_off = iter->off; return true; } if (VISIT_REGEX (iter, key, regex, options, data)) { return true; } } break; case BSON_TYPE_DBPOINTER: { uint32_t collection_len = 0; const char *collection = NULL; const bson_oid_t *oid = NULL; bson_iter_dbpointer (iter, &collection_len, &collection, &oid); if (!bson_utf8_validate (collection, collection_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_DBPOINTER ( iter, key, collection_len, collection, oid, data)) { return true; } } break; case BSON_TYPE_CODE: { uint32_t code_len; const char *code; code = bson_iter_code (iter, &code_len); if (!bson_utf8_validate (code, code_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_CODE (iter, key, code_len, code, data)) { return true; } } break; case BSON_TYPE_SYMBOL: { uint32_t symbol_len; const char *symbol; symbol = bson_iter_symbol (iter, &symbol_len); if (!bson_utf8_validate (symbol, symbol_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { return true; } } break; case BSON_TYPE_CODEWSCOPE: { uint32_t length = 0; const char *code; const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); if (!bson_utf8_validate (code, length, true)) { iter->err_off = iter->off; return true; } if (bson_init_static (&b, docbuf, doclen) && VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { return true; } } break; case BSON_TYPE_INT32: if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { return true; } break; case BSON_TYPE_TIMESTAMP: { uint32_t timestamp; uint32_t increment; bson_iter_timestamp (iter, &timestamp, &increment); if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { return true; } } break; case BSON_TYPE_INT64: if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { return true; } break; case BSON_TYPE_DECIMAL128: { bson_decimal128_t dec; bson_iter_decimal128 (iter, &dec); if (VISIT_DECIMAL128 (iter, key, &dec, data)) { return true; } } break; case BSON_TYPE_MAXKEY: if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_MINKEY: if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_EOD: default: break; } if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { return true; } } if (iter->err_off) { if (unsupported && visitor->visit_unsupported_type && bson_utf8_validate (key, strlen (key), false)) { visitor->visit_unsupported_type (iter, key, bson_type, data); return false; } VISIT_CORRUPT (iter, data); } #undef VISIT_FIELD return false; } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_bool -- * * Overwrites the current BSON_TYPE_BOOLEAN field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_bool (bson_iter_t *iter, /* IN */ bool value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { memcpy ((void *) (iter->raw + iter->d1), &value, 1); } } void bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { memcpy ( (void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); } } void bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment) { uint64_t value; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { value = ((((uint64_t) timestamp) << 32U) | ((uint64_t) increment)); value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } void bson_iter_overwrite_date_time (bson_iter_t *iter, int64_t value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int32 -- * * Overwrites the current BSON_TYPE_INT32 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int32 (bson_iter_t *iter, /* IN */ int32_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT32_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int64 -- * * Overwrites the current BSON_TYPE_INT64 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int64 (bson_iter_t *iter, /* IN */ int64_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT64_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_double -- * * Overwrites the current BSON_TYPE_DOUBLE field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_double (bson_iter_t *iter, /* IN */ double value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { value = BSON_DOUBLE_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_decimal128 -- * * Overwrites the current BSON_TYPE_DECIMAL128 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_decimal128 (bson_iter_t *iter, /* IN */ bson_decimal128_t *value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN uint64_t data[2]; data[0] = BSON_UINT64_TO_LE (value->low); data[1] = BSON_UINT64_TO_LE (value->high); memcpy ((void *) (iter->raw + iter->d1), data, sizeof (data)); #else memcpy ((void *) (iter->raw + iter->d1), value, sizeof (*value)); #endif } } /* *-------------------------------------------------------------------------- * * bson_iter_value -- * * Retrieves a bson_value_t containing the boxed value of the current * element. The result of this function valid until the state of * iter has been changed (through the use of bson_iter_next()). * * Returns: * A bson_value_t that should not be modified or freed. If you need * to hold on to the value, use bson_value_copy(). * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_value_t * bson_iter_value (bson_iter_t *iter) /* IN */ { bson_value_t *value; BSON_ASSERT (iter); value = &iter->value; value->value_type = ITER_TYPE (iter); switch (value->value_type) { case BSON_TYPE_DOUBLE: value->value.v_double = bson_iter_double (iter); break; case BSON_TYPE_UTF8: value->value.v_utf8.str = (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: bson_iter_document (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_ARRAY: bson_iter_array (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_BINARY: bson_iter_binary (iter, &value->value.v_binary.subtype, &value->value.v_binary.data_len, (const uint8_t **) &value->value.v_binary.data); break; case BSON_TYPE_OID: bson_oid_copy (bson_iter_oid (iter), &value->value.v_oid); break; case BSON_TYPE_BOOL: value->value.v_bool = bson_iter_bool (iter); break; case BSON_TYPE_DATE_TIME: value->value.v_datetime = bson_iter_date_time (iter); break; case BSON_TYPE_REGEX: value->value.v_regex.regex = (char *) bson_iter_regex ( iter, (const char **) &value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: { const bson_oid_t *oid; bson_iter_dbpointer (iter, &value->value.v_dbpointer.collection_len, (const char **) &value->value.v_dbpointer.collection, &oid); bson_oid_copy (oid, &value->value.v_dbpointer.oid); break; } case BSON_TYPE_CODE: value->value.v_code.code = (char *) bson_iter_code (iter, &value->value.v_code.code_len); break; case BSON_TYPE_SYMBOL: value->value.v_symbol.symbol = (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: value->value.v_codewscope.code = (char *) bson_iter_codewscope ( iter, &value->value.v_codewscope.code_len, &value->value.v_codewscope.scope_len, (const uint8_t **) &value->value.v_codewscope.scope_data); break; case BSON_TYPE_INT32: value->value.v_int32 = bson_iter_int32 (iter); break; case BSON_TYPE_TIMESTAMP: bson_iter_timestamp (iter, &value->value.v_timestamp.timestamp, &value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: value->value.v_int64 = bson_iter_int64 (iter); break; case BSON_TYPE_DECIMAL128: bson_iter_decimal128 (iter, &(value->value.v_decimal128)); break; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: break; case BSON_TYPE_EOD: default: return NULL; } return value; } uint32_t bson_iter_key_len (const bson_iter_t *iter) { /* * f i e l d n a m e \0 _ * ^ ^ * | | * iter->key iter->d1 * */ BSON_ASSERT (iter->d1 > iter->key); return iter->d1 - iter->key - 1; } bool bson_iter_init_from_data_at_offset (bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen) { const char *key; uint32_t bson_type; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = (uint32_t) length; iter->off = 0; iter->type = 0; iter->key = 0; iter->next_off = offset; iter->err_off = 0; if (!_bson_iter_next_internal ( iter, keylen, &key, &bson_type, &unsupported)) { memset (iter, 0, sizeof *iter); return false; } return true; } uint32_t bson_iter_offset (bson_iter_t *iter) { return iter->off; }
_bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; }
_bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o - 4)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; }
{'added': [(621, ' if (l >= (len - o - 4)) {')], 'deleted': [(621, ' if (l >= (len - o)) {')]}
1
1
1,259
6,917
https://github.com/mongodb/mongo-c-driver
CVE-2018-16790
['CWE-125']
qp.c
create_qp_common
/* * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/module.h> #include <rdma/ib_umem.h> #include <rdma/ib_cache.h> #include <rdma/ib_user_verbs.h> #include <linux/mlx5/fs.h> #include "mlx5_ib.h" #include "ib_rep.h" /* not supported currently */ static int wq_signature; enum { MLX5_IB_ACK_REQ_FREQ = 8, }; enum { MLX5_IB_DEFAULT_SCHED_QUEUE = 0x83, MLX5_IB_DEFAULT_QP0_SCHED_QUEUE = 0x3f, MLX5_IB_LINK_TYPE_IB = 0, MLX5_IB_LINK_TYPE_ETH = 1 }; enum { MLX5_IB_SQ_STRIDE = 6, MLX5_IB_SQ_UMR_INLINE_THRESHOLD = 64, }; static const u32 mlx5_ib_opcode[] = { [IB_WR_SEND] = MLX5_OPCODE_SEND, [IB_WR_LSO] = MLX5_OPCODE_LSO, [IB_WR_SEND_WITH_IMM] = MLX5_OPCODE_SEND_IMM, [IB_WR_RDMA_WRITE] = MLX5_OPCODE_RDMA_WRITE, [IB_WR_RDMA_WRITE_WITH_IMM] = MLX5_OPCODE_RDMA_WRITE_IMM, [IB_WR_RDMA_READ] = MLX5_OPCODE_RDMA_READ, [IB_WR_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_CS, [IB_WR_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_FA, [IB_WR_SEND_WITH_INV] = MLX5_OPCODE_SEND_INVAL, [IB_WR_LOCAL_INV] = MLX5_OPCODE_UMR, [IB_WR_REG_MR] = MLX5_OPCODE_UMR, [IB_WR_MASKED_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_MASKED_CS, [IB_WR_MASKED_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_MASKED_FA, [MLX5_IB_WR_UMR] = MLX5_OPCODE_UMR, }; struct mlx5_wqe_eth_pad { u8 rsvd0[16]; }; enum raw_qp_set_mask_map { MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID = 1UL << 0, MLX5_RAW_QP_RATE_LIMIT = 1UL << 1, }; struct mlx5_modify_raw_qp_param { u16 operation; u32 set_mask; /* raw_qp_set_mask_map */ struct mlx5_rate_limit rl; u8 rq_q_ctr_id; }; static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq); static int is_qp0(enum ib_qp_type qp_type) { return qp_type == IB_QPT_SMI; } static int is_sqp(enum ib_qp_type qp_type) { return is_qp0(qp_type) || is_qp1(qp_type); } static void *get_wqe(struct mlx5_ib_qp *qp, int offset) { return mlx5_buf_offset(&qp->buf, offset); } static void *get_recv_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->rq.offset + (n << qp->rq.wqe_shift)); } void *mlx5_get_send_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->sq.offset + (n << MLX5_IB_SQ_STRIDE)); } /** * mlx5_ib_read_user_wqe() - Copy a user-space WQE to kernel space. * * @qp: QP to copy from. * @send: copy from the send queue when non-zero, use the receive queue * otherwise. * @wqe_index: index to start copying from. For send work queues, the * wqe_index is in units of MLX5_SEND_WQE_BB. * For receive work queue, it is the number of work queue * element in the queue. * @buffer: destination buffer. * @length: maximum number of bytes to copy. * * Copies at least a single WQE, but may copy more data. * * Return: the number of bytes copied, or an error code. */ int mlx5_ib_read_user_wqe(struct mlx5_ib_qp *qp, int send, int wqe_index, void *buffer, u32 length, struct mlx5_ib_qp_base *base) { struct ib_device *ibdev = qp->ibqp.device; struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_wq *wq = send ? &qp->sq : &qp->rq; size_t offset; size_t wq_end; struct ib_umem *umem = base->ubuffer.umem; u32 first_copy_length; int wqe_length; int ret; if (wq->wqe_cnt == 0) { mlx5_ib_dbg(dev, "mlx5_ib_read_user_wqe for a QP with wqe_cnt == 0. qp_type: 0x%x\n", qp->ibqp.qp_type); return -EINVAL; } offset = wq->offset + ((wqe_index % wq->wqe_cnt) << wq->wqe_shift); wq_end = wq->offset + (wq->wqe_cnt << wq->wqe_shift); if (send && length < sizeof(struct mlx5_wqe_ctrl_seg)) return -EINVAL; if (offset > umem->length || (send && offset + sizeof(struct mlx5_wqe_ctrl_seg) > umem->length)) return -EINVAL; first_copy_length = min_t(u32, offset + length, wq_end) - offset; ret = ib_umem_copy_from(buffer, umem, offset, first_copy_length); if (ret) return ret; if (send) { struct mlx5_wqe_ctrl_seg *ctrl = buffer; int ds = be32_to_cpu(ctrl->qpn_ds) & MLX5_WQE_CTRL_DS_MASK; wqe_length = ds * MLX5_WQE_DS_UNITS; } else { wqe_length = 1 << wq->wqe_shift; } if (wqe_length <= first_copy_length) return first_copy_length; ret = ib_umem_copy_from(buffer + first_copy_length, umem, wq->offset, wqe_length - first_copy_length); if (ret) return ret; return wqe_length; } static void mlx5_ib_qp_event(struct mlx5_core_qp *qp, int type) { struct ib_qp *ibqp = &to_mibqp(qp)->ibqp; struct ib_event event; if (type == MLX5_EVENT_TYPE_PATH_MIG) { /* This event is only valid for trans_qps */ to_mibqp(qp)->port = to_mibqp(qp)->trans_qp.alt_port; } if (ibqp->event_handler) { event.device = ibqp->device; event.element.qp = ibqp; switch (type) { case MLX5_EVENT_TYPE_PATH_MIG: event.event = IB_EVENT_PATH_MIG; break; case MLX5_EVENT_TYPE_COMM_EST: event.event = IB_EVENT_COMM_EST; break; case MLX5_EVENT_TYPE_SQ_DRAINED: event.event = IB_EVENT_SQ_DRAINED; break; case MLX5_EVENT_TYPE_SRQ_LAST_WQE: event.event = IB_EVENT_QP_LAST_WQE_REACHED; break; case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_QP_FATAL; break; case MLX5_EVENT_TYPE_PATH_MIG_FAILED: event.event = IB_EVENT_PATH_MIG_ERR; break; case MLX5_EVENT_TYPE_WQ_INVAL_REQ_ERROR: event.event = IB_EVENT_QP_REQ_ERR; break; case MLX5_EVENT_TYPE_WQ_ACCESS_ERROR: event.event = IB_EVENT_QP_ACCESS_ERR; break; default: pr_warn("mlx5_ib: Unexpected event type %d on QP %06x\n", type, qp->qpn); return; } ibqp->event_handler(&event, ibqp->qp_context); } } static int set_rq_size(struct mlx5_ib_dev *dev, struct ib_qp_cap *cap, int has_rq, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd) { int wqe_size; int wq_size; /* Sanity check RQ size before proceeding */ if (cap->max_recv_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) return -EINVAL; if (!has_rq) { qp->rq.max_gs = 0; qp->rq.wqe_cnt = 0; qp->rq.wqe_shift = 0; cap->max_recv_wr = 0; cap->max_recv_sge = 0; } else { if (ucmd) { qp->rq.wqe_cnt = ucmd->rq_wqe_count; if (ucmd->rq_wqe_shift > BITS_PER_BYTE * sizeof(ucmd->rq_wqe_shift)) return -EINVAL; qp->rq.wqe_shift = ucmd->rq_wqe_shift; if ((1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) < qp->wq_sig) return -EINVAL; qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } else { wqe_size = qp->wq_sig ? sizeof(struct mlx5_wqe_signature_seg) : 0; wqe_size += cap->max_recv_sge * sizeof(struct mlx5_wqe_data_seg); wqe_size = roundup_pow_of_two(wqe_size); wq_size = roundup_pow_of_two(cap->max_recv_wr) * wqe_size; wq_size = max_t(int, wq_size, MLX5_SEND_WQE_BB); qp->rq.wqe_cnt = wq_size / wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)) { mlx5_ib_dbg(dev, "wqe_size %d, max %d\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)); return -EINVAL; } qp->rq.wqe_shift = ilog2(wqe_size); qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } } return 0; } static int sq_overhead(struct ib_qp_init_attr *attr) { int size = 0; switch (attr->qp_type) { case IB_QPT_XRC_INI: size += sizeof(struct mlx5_wqe_xrc_seg); /* fall through */ case IB_QPT_RC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_atomic_seg) + sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg) + MLX5_IB_SQ_UMR_INLINE_THRESHOLD / MLX5_IB_UMR_OCTOWORD); break; case IB_QPT_XRC_TGT: return 0; case IB_QPT_UC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg)); break; case IB_QPT_UD: if (attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO) size += sizeof(struct mlx5_wqe_eth_pad) + sizeof(struct mlx5_wqe_eth_seg); /* fall through */ case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_datagram_seg); break; case MLX5_IB_QPT_REG_UMR: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg); break; default: return -EINVAL; } return size; } static int calc_send_wqe(struct ib_qp_init_attr *attr) { int inl_size = 0; int size; size = sq_overhead(attr); if (size < 0) return size; if (attr->cap.max_inline_data) { inl_size = size + sizeof(struct mlx5_wqe_inline_seg) + attr->cap.max_inline_data; } size += attr->cap.max_send_sge * sizeof(struct mlx5_wqe_data_seg); if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN && ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB) < MLX5_SIG_WQE_SIZE) return MLX5_SIG_WQE_SIZE; else return ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB); } static int get_send_sge(struct ib_qp_init_attr *attr, int wqe_size) { int max_sge; if (attr->qp_type == IB_QPT_RC) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else if (attr->qp_type == IB_QPT_XRC_INI) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_xrc_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else max_sge = (wqe_size - sq_overhead(attr)) / sizeof(struct mlx5_wqe_data_seg); return min_t(int, max_sge, wqe_size - sq_overhead(attr) / sizeof(struct mlx5_wqe_data_seg)); } static int calc_sq_size(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *attr, struct mlx5_ib_qp *qp) { int wqe_size; int wq_size; if (!attr->cap.max_send_wr) return 0; wqe_size = calc_send_wqe(attr); mlx5_ib_dbg(dev, "wqe_size %d\n", wqe_size); if (wqe_size < 0) return wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_dbg(dev, "wqe_size(%d) > max_sq_desc_sz(%d)\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } qp->max_inline_data = wqe_size - sq_overhead(attr) - sizeof(struct mlx5_wqe_inline_seg); attr->cap.max_inline_data = qp->max_inline_data; if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN) qp->signature_en = true; wq_size = roundup_pow_of_two(attr->cap.max_send_wr * wqe_size); qp->sq.wqe_cnt = wq_size / MLX5_SEND_WQE_BB; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_dbg(dev, "send queue size (%d * %d / %d -> %d) exceeds limits(%d)\n", attr->cap.max_send_wr, wqe_size, MLX5_SEND_WQE_BB, qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -ENOMEM; } qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.max_gs = get_send_sge(attr, wqe_size); if (qp->sq.max_gs < attr->cap.max_send_sge) return -ENOMEM; attr->cap.max_send_sge = qp->sq.max_gs; qp->sq.max_post = wq_size / wqe_size; attr->cap.max_send_wr = qp->sq.max_post; return wq_size; } static int set_user_buf_size(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd, struct mlx5_ib_qp_base *base, struct ib_qp_init_attr *attr) { int desc_sz = 1 << qp->sq.wqe_shift; if (desc_sz > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_warn(dev, "desc_sz %d, max_sq_desc_sz %d\n", desc_sz, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } if (ucmd->sq_wqe_count && ((1 << ilog2(ucmd->sq_wqe_count)) != ucmd->sq_wqe_count)) { mlx5_ib_warn(dev, "sq_wqe_count %d, sq_wqe_count %d\n", ucmd->sq_wqe_count, ucmd->sq_wqe_count); return -EINVAL; } qp->sq.wqe_cnt = ucmd->sq_wqe_count; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_warn(dev, "wqe_cnt %d, max_wqes %d\n", qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -EINVAL; } if (attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { base->ubuffer.buf_size = qp->rq.wqe_cnt << qp->rq.wqe_shift; qp->raw_packet_qp.sq.ubuffer.buf_size = qp->sq.wqe_cnt << 6; } else { base->ubuffer.buf_size = (qp->rq.wqe_cnt << qp->rq.wqe_shift) + (qp->sq.wqe_cnt << 6); } return 0; } static int qp_has_rq(struct ib_qp_init_attr *attr) { if (attr->qp_type == IB_QPT_XRC_INI || attr->qp_type == IB_QPT_XRC_TGT || attr->srq || attr->qp_type == MLX5_IB_QPT_REG_UMR || !attr->cap.max_recv_wr) return 0; return 1; } enum { /* this is the first blue flame register in the array of bfregs assigned * to a processes. Since we do not use it for blue flame but rather * regular 64 bit doorbells, we do not need a lock for maintaiing * "odd/even" order */ NUM_NON_BLUE_FLAME_BFREGS = 1, }; static int max_bfregs(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return get_num_static_uars(dev, bfregi) * MLX5_NON_FP_BFREGS_PER_UAR; } static int num_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int n; n = max_bfregs(dev, bfregi) - bfregi->num_low_latency_bfregs - NUM_NON_BLUE_FLAME_BFREGS; return n >= 0 ? n : 0; } static int first_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return num_med_bfreg(dev, bfregi) ? 1 : -ENOMEM; } static int first_hi_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int med; med = num_med_bfreg(dev, bfregi); return ++med; } static int alloc_high_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int i; for (i = first_hi_bfreg(dev, bfregi); i < max_bfregs(dev, bfregi); i++) { if (!bfregi->count[i]) { bfregi->count[i]++; return i; } } return -ENOMEM; } static int alloc_med_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int minidx = first_med_bfreg(dev, bfregi); int i; if (minidx < 0) return minidx; for (i = minidx; i < first_hi_bfreg(dev, bfregi); i++) { if (bfregi->count[i] < bfregi->count[minidx]) minidx = i; if (!bfregi->count[minidx]) break; } bfregi->count[minidx]++; return minidx; } static int alloc_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int bfregn = -ENOMEM; mutex_lock(&bfregi->lock); if (bfregi->ver >= 2) { bfregn = alloc_high_class_bfreg(dev, bfregi); if (bfregn < 0) bfregn = alloc_med_class_bfreg(dev, bfregi); } if (bfregn < 0) { BUILD_BUG_ON(NUM_NON_BLUE_FLAME_BFREGS != 1); bfregn = 0; bfregi->count[bfregn]++; } mutex_unlock(&bfregi->lock); return bfregn; } void mlx5_ib_free_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { mutex_lock(&bfregi->lock); bfregi->count[bfregn]--; mutex_unlock(&bfregi->lock); } static enum mlx5_qp_state to_mlx5_state(enum ib_qp_state state) { switch (state) { case IB_QPS_RESET: return MLX5_QP_STATE_RST; case IB_QPS_INIT: return MLX5_QP_STATE_INIT; case IB_QPS_RTR: return MLX5_QP_STATE_RTR; case IB_QPS_RTS: return MLX5_QP_STATE_RTS; case IB_QPS_SQD: return MLX5_QP_STATE_SQD; case IB_QPS_SQE: return MLX5_QP_STATE_SQER; case IB_QPS_ERR: return MLX5_QP_STATE_ERR; default: return -1; } } static int to_mlx5_st(enum ib_qp_type type) { switch (type) { case IB_QPT_RC: return MLX5_QP_ST_RC; case IB_QPT_UC: return MLX5_QP_ST_UC; case IB_QPT_UD: return MLX5_QP_ST_UD; case MLX5_IB_QPT_REG_UMR: return MLX5_QP_ST_REG_UMR; case IB_QPT_XRC_INI: case IB_QPT_XRC_TGT: return MLX5_QP_ST_XRC; case IB_QPT_SMI: return MLX5_QP_ST_QP0; case MLX5_IB_QPT_HW_GSI: return MLX5_QP_ST_QP1; case MLX5_IB_QPT_DCI: return MLX5_QP_ST_DCI; case IB_QPT_RAW_IPV6: return MLX5_QP_ST_RAW_IPV6; case IB_QPT_RAW_PACKET: case IB_QPT_RAW_ETHERTYPE: return MLX5_QP_ST_RAW_ETHERTYPE; case IB_QPT_MAX: default: return -EINVAL; } } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); int bfregn_to_uar_index(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, u32 bfregn, bool dyn_bfreg) { unsigned int bfregs_per_sys_page; u32 index_of_sys_page; u32 offset; bfregs_per_sys_page = get_uars_per_sys_page(dev, bfregi->lib_uar_4k) * MLX5_NON_FP_BFREGS_PER_UAR; index_of_sys_page = bfregn / bfregs_per_sys_page; if (dyn_bfreg) { index_of_sys_page += bfregi->num_static_sys_pages; if (index_of_sys_page >= bfregi->num_sys_pages) return -EINVAL; if (bfregn > bfregi->num_dyn_bfregs || bfregi->sys_pages[index_of_sys_page] == MLX5_IB_INVALID_UAR_INDEX) { mlx5_ib_dbg(dev, "Invalid dynamic uar index\n"); return -EINVAL; } } offset = bfregn % bfregs_per_sys_page / MLX5_NON_FP_BFREGS_PER_UAR; return bfregi->sys_pages[index_of_sys_page] + offset; } static int mlx5_ib_umem_get(struct mlx5_ib_dev *dev, struct ib_pd *pd, unsigned long addr, size_t size, struct ib_umem **umem, int *npages, int *page_shift, int *ncont, u32 *offset) { int err; *umem = ib_umem_get(pd->uobject->context, addr, size, 0, 0); if (IS_ERR(*umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); return PTR_ERR(*umem); } mlx5_ib_cont_pages(*umem, addr, 0, npages, page_shift, ncont, NULL); err = mlx5_ib_get_buf_offset(addr, *page_shift, offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } mlx5_ib_dbg(dev, "addr 0x%lx, size %zu, npages %d, page_shift %d, ncont %d, offset %d\n", addr, size, *npages, *page_shift, *ncont, *offset); return 0; err_umem: ib_umem_release(*umem); *umem = NULL; return err; } static void destroy_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_ucontext *context; if (rwq->create_flags & MLX5_IB_WQ_FLAGS_DELAY_DROP) atomic_dec(&dev->delay_drop.rqs_cnt); context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &rwq->db); if (rwq->umem) ib_umem_release(rwq->umem); } static int create_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq, struct mlx5_ib_create_wq *ucmd) { struct mlx5_ib_ucontext *context; int page_shift = 0; int npages; u32 offset = 0; int ncont = 0; int err; if (!ucmd->buf_addr) return -EINVAL; context = to_mucontext(pd->uobject->context); rwq->umem = ib_umem_get(pd->uobject->context, ucmd->buf_addr, rwq->buf_size, 0, 0); if (IS_ERR(rwq->umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); err = PTR_ERR(rwq->umem); return err; } mlx5_ib_cont_pages(rwq->umem, ucmd->buf_addr, 0, &npages, &page_shift, &ncont, NULL); err = mlx5_ib_get_buf_offset(ucmd->buf_addr, page_shift, &rwq->rq_page_offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } rwq->rq_num_pas = ncont; rwq->page_shift = page_shift; rwq->log_page_size = page_shift - MLX5_ADAPTER_PAGE_SHIFT; rwq->wq_sig = !!(ucmd->flags & MLX5_WQ_FLAG_SIGNATURE); mlx5_ib_dbg(dev, "addr 0x%llx, size %zd, npages %d, page_shift %d, ncont %d, offset %d\n", (unsigned long long)ucmd->buf_addr, rwq->buf_size, npages, page_shift, ncont, offset); err = mlx5_ib_db_map_user(context, ucmd->db_addr, &rwq->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_umem; } rwq->create_type = MLX5_WQ_USER; return 0; err_umem: ib_umem_release(rwq->umem); return err; } static int adjust_bfregn(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { return bfregn / MLX5_NON_FP_BFREGS_PER_UAR * MLX5_BFREGS_PER_UAR + bfregn % MLX5_NON_FP_BFREGS_PER_UAR; } static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct ib_udata *udata, struct ib_qp_init_attr *attr, u32 **in, struct mlx5_ib_create_qp_resp *resp, int *inlen, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_ubuffer *ubuffer = &base->ubuffer; int page_shift = 0; int uar_index = 0; int npages; u32 offset = 0; int bfregn; int ncont = 0; __be64 *pas; void *qpc; int err; err = ib_copy_from_udata(&ucmd, udata, sizeof(ucmd)); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return err; } context = to_mucontext(pd->uobject->context); if (ucmd.flags & MLX5_QP_FLAG_BFREG_INDEX) { uar_index = bfregn_to_uar_index(dev, &context->bfregi, ucmd.bfreg_index, true); if (uar_index < 0) return uar_index; bfregn = MLX5_IB_INVALID_BFREG; } else if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) { /* * TBD: should come from the verbs when we have the API */ /* In CROSS_CHANNEL CQ and QP must use the same UAR */ bfregn = MLX5_CROSS_CHANNEL_BFREG; } else { bfregn = alloc_bfreg(dev, &context->bfregi); if (bfregn < 0) return bfregn; } mlx5_ib_dbg(dev, "bfregn 0x%x, uar_index 0x%x\n", bfregn, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) uar_index = bfregn_to_uar_index(dev, &context->bfregi, bfregn, false); qp->rq.offset = 0; qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; err = set_user_buf_size(dev, qp, &ucmd, base, attr); if (err) goto err_bfreg; if (ucmd.buf_addr && ubuffer->buf_size) { ubuffer->buf_addr = ucmd.buf_addr; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &ubuffer->umem, &npages, &page_shift, &ncont, &offset); if (err) goto err_bfreg; } else { ubuffer->umem = NULL; } *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * ncont; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_umem; } pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas); if (ubuffer->umem) mlx5_ib_populate_pas(dev, ubuffer->umem, page_shift, pas, 0); qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, log_page_size, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(qpc, qpc, page_offset, offset); MLX5_SET(qpc, qpc, uar_page, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) resp->bfreg_index = adjust_bfregn(dev, &context->bfregi, bfregn); else resp->bfreg_index = MLX5_IB_INVALID_BFREG; qp->bfregn = bfregn; err = mlx5_ib_db_map_user(context, ucmd.db_addr, &qp->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_free; } err = ib_copy_to_udata(udata, resp, min(udata->outlen, sizeof(*resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); goto err_unmap; } qp->create_type = MLX5_QP_USER; return 0; err_unmap: mlx5_ib_db_unmap_user(context, &qp->db); err_free: kvfree(*in); err_umem: if (ubuffer->umem) ib_umem_release(ubuffer->umem); err_bfreg: if (bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, bfregn); return err; } static void destroy_qp_user(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &qp->db); if (base->ubuffer.umem) ib_umem_release(base->ubuffer.umem); /* * Free only the BFREGs which are handled by the kernel. * BFREGs of UARs allocated dynamically are handled by user. */ if (qp->bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, qp->bfregn); } static int create_kernel_qp(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_qp *qp, u32 **in, int *inlen, struct mlx5_ib_qp_base *base) { int uar_index; void *qpc; int err; if (init_attr->create_flags & ~(IB_QP_CREATE_SIGNATURE_EN | IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK | IB_QP_CREATE_IPOIB_UD_LSO | IB_QP_CREATE_NETIF_QP | mlx5_ib_create_qp_sqpn_qp1())) return -EINVAL; if (init_attr->qp_type == MLX5_IB_QPT_REG_UMR) qp->bf.bfreg = &dev->fp_bfreg; else qp->bf.bfreg = &dev->bfreg; /* We need to divide by two since each register is comprised of * two buffers of identical size, namely odd and even */ qp->bf.buf_size = (1 << MLX5_CAP_GEN(dev->mdev, log_bf_reg_size)) / 2; uar_index = qp->bf.bfreg->index; err = calc_sq_size(dev, init_attr, qp); if (err < 0) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->rq.offset = 0; qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; base->ubuffer.buf_size = err + (qp->rq.wqe_cnt << qp->rq.wqe_shift); err = mlx5_buf_alloc(dev->mdev, base->ubuffer.buf_size, &qp->buf); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->sq.qend = mlx5_get_send_wqe(qp, qp->sq.wqe_cnt); *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * qp->buf.npages; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_buf; } qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, uar_page, uar_index); MLX5_SET(qpc, qpc, log_page_size, qp->buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT); /* Set "fast registration enabled" for all kernel QPs */ MLX5_SET(qpc, qpc, fre, 1); MLX5_SET(qpc, qpc, rlky, 1); if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { MLX5_SET(qpc, qpc, deth_sqpn, 1); qp->flags |= MLX5_IB_QP_SQPN_QP1; } mlx5_fill_page_array(&qp->buf, (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas)); err = mlx5_db_alloc(dev->mdev, &qp->db); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); goto err_free; } qp->sq.wrid = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wrid), GFP_KERNEL); qp->sq.wr_data = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wr_data), GFP_KERNEL); qp->rq.wrid = kvmalloc_array(qp->rq.wqe_cnt, sizeof(*qp->rq.wrid), GFP_KERNEL); qp->sq.w_list = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.w_list), GFP_KERNEL); qp->sq.wqe_head = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wqe_head), GFP_KERNEL); if (!qp->sq.wrid || !qp->sq.wr_data || !qp->rq.wrid || !qp->sq.w_list || !qp->sq.wqe_head) { err = -ENOMEM; goto err_wrid; } qp->create_type = MLX5_QP_KERNEL; return 0; err_wrid: kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); err_free: kvfree(*in); err_buf: mlx5_buf_free(dev->mdev, &qp->buf); return err; } static void destroy_qp_kernel(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); mlx5_buf_free(dev->mdev, &qp->buf); } static u32 get_rx_type(struct mlx5_ib_qp *qp, struct ib_qp_init_attr *attr) { if (attr->srq || (attr->qp_type == IB_QPT_XRC_TGT) || (attr->qp_type == MLX5_IB_QPT_DCI) || (attr->qp_type == IB_QPT_XRC_INI)) return MLX5_SRQ_RQ; else if (!qp->has_rq) return MLX5_ZERO_LEN_RQ; else return MLX5_NON_ZERO_RQ; } static int is_connected(enum ib_qp_type qp_type) { if (qp_type == IB_QPT_RC || qp_type == IB_QPT_UC) return 1; return 0; } static int create_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_sq *sq, u32 tdn) { u32 in[MLX5_ST_SZ_DW(create_tis_in)] = {0}; void *tisc = MLX5_ADDR_OF(create_tis_in, in, ctx); MLX5_SET(tisc, tisc, transport_domain, tdn); if (qp->flags & MLX5_IB_QP_UNDERLAY) MLX5_SET(tisc, tisc, underlay_qpn, qp->underlay_qpn); return mlx5_core_create_tis(dev->mdev, in, sizeof(in), &sq->tisn); } static void destroy_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { mlx5_core_destroy_tis(dev->mdev, sq->tisn); } static void destroy_flow_rule_vport_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { if (sq->flow_rule) mlx5_del_flow_rules(sq->flow_rule); } static int create_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, void *qpin, struct ib_pd *pd) { struct mlx5_ib_ubuffer *ubuffer = &sq->ubuffer; __be64 *pas; void *in; void *sqc; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); void *wq; int inlen; int err; int page_shift = 0; int npages; int ncont = 0; u32 offset = 0; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &sq->ubuffer.umem, &npages, &page_shift, &ncont, &offset); if (err) return err; inlen = MLX5_ST_SZ_BYTES(create_sq_in) + sizeof(u64) * ncont; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err_umem; } sqc = MLX5_ADDR_OF(create_sq_in, in, ctx); MLX5_SET(sqc, sqc, flush_in_error_en, 1); if (MLX5_CAP_ETH(dev->mdev, multi_pkt_send_wqe)) MLX5_SET(sqc, sqc, allow_multi_pkt_send_wqe, 1); MLX5_SET(sqc, sqc, state, MLX5_SQC_STATE_RST); MLX5_SET(sqc, sqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(sqc, sqc, cqn, MLX5_GET(qpc, qpc, cqn_snd)); MLX5_SET(sqc, sqc, tis_lst_sz, 1); MLX5_SET(sqc, sqc, tis_num_0, sq->tisn); if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, swp)) MLX5_SET(sqc, sqc, allow_swp, 1); wq = MLX5_ADDR_OF(sqc, sqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET(wq, wq, uar_page, MLX5_GET(qpc, qpc, uar_page)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, ilog2(MLX5_SEND_WQE_BB)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_sq_size)); MLX5_SET(wq, wq, log_wq_pg_sz, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(wq, wq, page_offset, offset); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, sq->ubuffer.umem, page_shift, pas, 0); err = mlx5_core_create_sq_tracked(dev->mdev, in, inlen, &sq->base.mqp); kvfree(in); if (err) goto err_umem; err = create_flow_rule_vport_sq(dev, sq); if (err) goto err_flow; return 0; err_flow: mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); err_umem: ib_umem_release(sq->ubuffer.umem); sq->ubuffer.umem = NULL; return err; } static void destroy_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { destroy_flow_rule_vport_sq(dev, sq); mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); ib_umem_release(sq->ubuffer.umem); } static size_t get_rq_pas_size(void *qpc) { u32 log_page_size = MLX5_GET(qpc, qpc, log_page_size) + 12; u32 log_rq_stride = MLX5_GET(qpc, qpc, log_rq_stride); u32 log_rq_size = MLX5_GET(qpc, qpc, log_rq_size); u32 page_offset = MLX5_GET(qpc, qpc, page_offset); u32 po_quanta = 1 << (log_page_size - 6); u32 rq_sz = 1 << (log_rq_size + 4 + log_rq_stride); u32 page_size = 1 << log_page_size; u32 rq_sz_po = rq_sz + (page_offset * po_quanta); u32 rq_num_pas = (rq_sz_po + page_size - 1) / page_size; return rq_num_pas * sizeof(u64); } static int create_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, void *qpin, size_t qpinlen) { struct mlx5_ib_qp *mqp = rq->base.container_mibqp; __be64 *pas; __be64 *qp_pas; void *in; void *rqc; void *wq; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); size_t rq_pas_size = get_rq_pas_size(qpc); size_t inlen; int err; if (qpinlen < rq_pas_size + MLX5_BYTE_OFF(create_qp_in, pas)) return -EINVAL; inlen = MLX5_ST_SZ_BYTES(create_rq_in) + rq_pas_size; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); if (!(rq->flags & MLX5_IB_RQ_CVLAN_STRIPPING)) MLX5_SET(rqc, rqc, vsd, 1); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); MLX5_SET(rqc, rqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(rqc, rqc, cqn, MLX5_GET(qpc, qpc, cqn_rcv)); if (mqp->flags & MLX5_IB_QP_CAP_SCATTER_FCS) MLX5_SET(rqc, rqc, scatter_fcs, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); if (rq->flags & MLX5_IB_RQ_PCI_WRITE_END_PADDING) MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); MLX5_SET(wq, wq, page_offset, MLX5_GET(qpc, qpc, page_offset)); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, MLX5_GET(qpc, qpc, log_rq_stride) + 4); MLX5_SET(wq, wq, log_wq_pg_sz, MLX5_GET(qpc, qpc, log_page_size)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_rq_size)); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); qp_pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, qpin, pas); memcpy(pas, qp_pas, rq_pas_size); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rq->base.mqp); kvfree(in); return err; } static void destroy_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_rq_tracked(dev->mdev, &rq->base.mqp); } static bool tunnel_offload_supported(struct mlx5_core_dev *dev) { return (MLX5_CAP_ETH(dev, tunnel_stateless_vxlan) || MLX5_CAP_ETH(dev, tunnel_stateless_gre) || MLX5_CAP_ETH(dev, tunnel_stateless_geneve_rx)); } static int create_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u32 tdn, bool tunnel_offload_en) { u32 *in; void *tirc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_DIRECT); MLX5_SET(tirc, tirc, inline_rqn, rq->base.mqp.qpn); MLX5_SET(tirc, tirc, transport_domain, tdn); if (tunnel_offload_en) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &rq->tirn); kvfree(in); return err; } static void destroy_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_tir(dev->mdev, rq->tirn); } static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u32 *in, size_t inlen, struct ib_pd *pd) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); int err; u32 tdn = mucontext->tdn; if (qp->sq.wqe_cnt) { err = create_raw_packet_qp_tis(dev, qp, sq, tdn); if (err) return err; err = create_raw_packet_qp_sq(dev, sq, in, pd); if (err) goto err_destroy_tis; sq->base.container_mibqp = qp; sq->base.mqp.event = mlx5_ib_qp_event; } if (qp->rq.wqe_cnt) { rq->base.container_mibqp = qp; if (qp->flags & MLX5_IB_QP_CVLAN_STRIPPING) rq->flags |= MLX5_IB_RQ_CVLAN_STRIPPING; if (qp->flags & MLX5_IB_QP_PCI_WRITE_END_PADDING) rq->flags |= MLX5_IB_RQ_PCI_WRITE_END_PADDING; err = create_raw_packet_qp_rq(dev, rq, in, inlen); if (err) goto err_destroy_sq; err = create_raw_packet_qp_tir(dev, rq, tdn, qp->tunnel_offload_en); if (err) goto err_destroy_rq; } qp->trans_qp.base.mqp.qpn = qp->sq.wqe_cnt ? sq->base.mqp.qpn : rq->base.mqp.qpn; return 0; err_destroy_rq: destroy_raw_packet_qp_rq(dev, rq); err_destroy_sq: if (!qp->sq.wqe_cnt) return err; destroy_raw_packet_qp_sq(dev, sq); err_destroy_tis: destroy_raw_packet_qp_tis(dev, sq); return err; } static void destroy_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; if (qp->rq.wqe_cnt) { destroy_raw_packet_qp_tir(dev, rq); destroy_raw_packet_qp_rq(dev, rq); } if (qp->sq.wqe_cnt) { destroy_raw_packet_qp_sq(dev, sq); destroy_raw_packet_qp_tis(dev, sq); } } static void raw_packet_qp_copy_info(struct mlx5_ib_qp *qp, struct mlx5_ib_raw_packet_qp *raw_packet_qp) { struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; sq->sq = &qp->sq; rq->rq = &qp->rq; sq->doorbell = &qp->db; rq->doorbell = &qp->db; } static void destroy_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { mlx5_core_destroy_tir(dev->mdev, qp->rss_qp.tirn); } static int create_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata) { struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); struct mlx5_ib_create_qp_resp resp = {}; int inlen; int err; u32 *in; void *tirc; void *hfso; u32 selected_fields = 0; u32 outer_l4; size_t min_resp_len; u32 tdn = mucontext->tdn; struct mlx5_ib_create_qp_rss ucmd = {}; size_t required_cmd_sz; if (init_attr->qp_type != IB_QPT_RAW_PACKET) return -EOPNOTSUPP; if (init_attr->create_flags || init_attr->send_cq) return -EINVAL; min_resp_len = offsetof(typeof(resp), bfreg_index) + sizeof(resp.bfreg_index); if (udata->outlen < min_resp_len) return -EINVAL; required_cmd_sz = offsetof(typeof(ucmd), flags) + sizeof(ucmd.flags); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } if (ucmd.flags & ~MLX5_QP_FLAG_TUNNEL_OFFLOADS) { mlx5_ib_dbg(dev, "invalid flags\n"); return -EOPNOTSUPP; } if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS && !tunnel_offload_supported(dev->mdev)) { mlx5_ib_dbg(dev, "tunnel offloads isn't supported\n"); return -EOPNOTSUPP; } if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER && !(ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS)) { mlx5_ib_dbg(dev, "Tunnel offloads must be set for inner RSS\n"); return -EOPNOTSUPP; } err = ib_copy_to_udata(udata, &resp, min(udata->outlen, sizeof(resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return -EINVAL; } inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_INDIRECT); MLX5_SET(tirc, tirc, indirect_table, init_attr->rwq_ind_tbl->ind_tbl_num); MLX5_SET(tirc, tirc, transport_domain, tdn); hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER) hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_inner); else hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); switch (ucmd.rx_hash_function) { case MLX5_RX_HASH_FUNC_TOEPLITZ: { void *rss_key = MLX5_ADDR_OF(tirc, tirc, rx_hash_toeplitz_key); size_t len = MLX5_FLD_SZ_BYTES(tirc, rx_hash_toeplitz_key); if (len != ucmd.rx_key_len) { err = -EINVAL; goto err; } MLX5_SET(tirc, tirc, rx_hash_fn, MLX5_RX_HASH_FN_TOEPLITZ); MLX5_SET(tirc, tirc, rx_hash_symmetric, 1); memcpy(rss_key, ucmd.rx_hash_key, len); break; } default: err = -EOPNOTSUPP; goto err; } if (!ucmd.rx_hash_fields_mask) { /* special case when this TIR serves as steering entry without hashing */ if (!init_attr->rwq_ind_tbl->log_ind_tbl_size) goto create_tir; err = -EINVAL; goto err; } if (((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) && ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6))) { err = -EINVAL; goto err; } /* If none of IPV4 & IPV6 SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV4); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV6); outer_l4 = ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) << 0 | ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) << 1 | (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) << 2; /* Check that only one l4 protocol is set */ if (outer_l4 & (outer_l4 - 1)) { err = -EINVAL; goto err; } /* If none of TCP & UDP SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_TCP); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_UDP); if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_SRC_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_DST_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_SPORT; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_DPORT; if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) selected_fields |= MLX5_HASH_FIELD_SEL_IPSEC_SPI; MLX5_SET(rx_hash_field_select, hfso, selected_fields, selected_fields); create_tir: if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &qp->rss_qp.tirn); if (err) goto err; kvfree(in); /* qpn is reserved for that QP */ qp->trans_qp.base.mqp.qpn = 0; qp->flags |= MLX5_IB_QP_RSS; return 0; err: kvfree(in); return err; } static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __acquires(&send_cq->lock) __acquires(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); spin_lock_nested(&recv_cq->lock, SINGLE_DEPTH_NESTING); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } else { spin_lock(&recv_cq->lock); spin_lock_nested(&send_cq->lock, SINGLE_DEPTH_NESTING); } } else { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } } else if (recv_cq) { spin_lock(&recv_cq->lock); __acquire(&send_cq->lock); } else { __acquire(&send_cq->lock); __acquire(&recv_cq->lock); } } static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __releases(&send_cq->lock) __releases(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_unlock(&recv_cq->lock); spin_unlock(&send_cq->lock); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } else { spin_unlock(&send_cq->lock); spin_unlock(&recv_cq->lock); } } else { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } } else if (recv_cq) { __release(&send_cq->lock); spin_unlock(&recv_cq->lock); } else { __release(&recv_cq->lock); __release(&send_cq->lock); } } static struct mlx5_ib_pd *get_pd(struct mlx5_ib_qp *qp) { return to_mpd(qp->ibqp.pd); } static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq) { switch (qp_type) { case IB_QPT_XRC_TGT: *send_cq = NULL; *recv_cq = NULL; break; case MLX5_IB_QPT_REG_UMR: case IB_QPT_XRC_INI: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = NULL; break; case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_RAW_PACKET: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = ib_recv_cq ? to_mcq(ib_recv_cq) : NULL; break; case IB_QPT_MAX: default: *send_cq = NULL; *recv_cq = NULL; break; } } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 lag_tx_affinity); static void destroy_qp_common(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_ib_qp_base *base; unsigned long flags; int err; if (qp->ibqp.rwq_ind_tbl) { destroy_rss_raw_qp_tir(dev, qp); return; } base = (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; if (qp->state != IB_QPS_RESET) { if (qp->ibqp.qp_type != IB_QPT_RAW_PACKET && !(qp->flags & MLX5_IB_QP_UNDERLAY)) { err = mlx5_core_qp_modify(dev->mdev, MLX5_CMD_OP_2RST_QP, 0, NULL, &base->mqp); } else { struct mlx5_modify_raw_qp_param raw_qp_param = { .operation = MLX5_CMD_OP_2RST_QP }; err = modify_raw_packet_qp(dev, qp, &raw_qp_param, 0); } if (err) mlx5_ib_warn(dev, "mlx5_ib: modify QP 0x%06x to RESET failed\n", base->mqp.qpn); } get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* del from lists under both locks above to protect reset flow paths */ list_del(&qp->qps_list); if (send_cq) list_del(&qp->cq_send_list); if (recv_cq) list_del(&qp->cq_recv_list); if (qp->create_type == MLX5_QP_KERNEL) { __mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL); if (send_cq != recv_cq) __mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); } mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { destroy_raw_packet_qp(dev, qp); } else { err = mlx5_core_destroy_qp(dev->mdev, &base->mqp); if (err) mlx5_ib_warn(dev, "failed to destroy QP 0x%x\n", base->mqp.qpn); } if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); else if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, &get_pd(qp)->ibpd, qp, base); } static const char *ib_qp_type_str(enum ib_qp_type type) { switch (type) { case IB_QPT_SMI: return "IB_QPT_SMI"; case IB_QPT_GSI: return "IB_QPT_GSI"; case IB_QPT_RC: return "IB_QPT_RC"; case IB_QPT_UC: return "IB_QPT_UC"; case IB_QPT_UD: return "IB_QPT_UD"; case IB_QPT_RAW_IPV6: return "IB_QPT_RAW_IPV6"; case IB_QPT_RAW_ETHERTYPE: return "IB_QPT_RAW_ETHERTYPE"; case IB_QPT_XRC_INI: return "IB_QPT_XRC_INI"; case IB_QPT_XRC_TGT: return "IB_QPT_XRC_TGT"; case IB_QPT_RAW_PACKET: return "IB_QPT_RAW_PACKET"; case MLX5_IB_QPT_REG_UMR: return "MLX5_IB_QPT_REG_UMR"; case IB_QPT_DRIVER: return "IB_QPT_DRIVER"; case IB_QPT_MAX: default: return "Invalid QP type"; } } static struct ib_qp *mlx5_ib_create_dct(struct ib_pd *pd, struct ib_qp_init_attr *attr, struct mlx5_ib_create_qp *ucmd) { struct mlx5_ib_qp *qp; int err = 0; u32 uidx = MLX5_IB_DEFAULT_UIDX; void *dctc; if (!attr->srq || !attr->recv_cq) return ERR_PTR(-EINVAL); err = get_qp_user_index(to_mucontext(pd->uobject->context), ucmd, sizeof(*ucmd), &uidx); if (err) return ERR_PTR(err); qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); qp->dct.in = kzalloc(MLX5_ST_SZ_BYTES(create_dct_in), GFP_KERNEL); if (!qp->dct.in) { err = -ENOMEM; goto err_free; } dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); qp->qp_sub_type = MLX5_IB_QPT_DCT; MLX5_SET(dctc, dctc, pd, to_mpd(pd)->pdn); MLX5_SET(dctc, dctc, srqn_xrqn, to_msrq(attr->srq)->msrq.srqn); MLX5_SET(dctc, dctc, cqn, to_mcq(attr->recv_cq)->mcq.cqn); MLX5_SET64(dctc, dctc, dc_access_key, ucmd->access_key); MLX5_SET(dctc, dctc, user_index, uidx); qp->state = IB_QPS_RESET; return &qp->ibqp; err_free: kfree(qp); return ERR_PTR(err); } static int set_mlx_qp_type(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_create_qp *ucmd, struct ib_udata *udata) { enum { MLX_QP_FLAGS = MLX5_QP_FLAG_TYPE_DCT | MLX5_QP_FLAG_TYPE_DCI }; int err; if (!udata) return -EINVAL; if (udata->inlen < sizeof(*ucmd)) { mlx5_ib_dbg(dev, "create_qp user command is smaller than expected\n"); return -EINVAL; } err = ib_copy_from_udata(ucmd, udata, sizeof(*ucmd)); if (err) return err; if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCI) { init_attr->qp_type = MLX5_IB_QPT_DCI; } else { if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCT) { init_attr->qp_type = MLX5_IB_QPT_DCT; } else { mlx5_ib_dbg(dev, "Invalid QP flags\n"); return -EINVAL; } } if (!MLX5_CAP_GEN(dev->mdev, dct)) { mlx5_ib_dbg(dev, "DC transport is not supported\n"); return -EOPNOTSUPP; } return 0; } struct ib_qp *mlx5_ib_create_qp(struct ib_pd *pd, struct ib_qp_init_attr *verbs_init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_qp *qp; u16 xrcdn = 0; int err; struct ib_qp_init_attr mlx_init_attr; struct ib_qp_init_attr *init_attr = verbs_init_attr; if (pd) { dev = to_mdev(pd->device); if (init_attr->qp_type == IB_QPT_RAW_PACKET) { if (!pd->uobject) { mlx5_ib_dbg(dev, "Raw Packet QP is not supported for kernel consumers\n"); return ERR_PTR(-EINVAL); } else if (!to_mucontext(pd->uobject->context)->cqe_version) { mlx5_ib_dbg(dev, "Raw Packet QP is only supported for CQE version > 0\n"); return ERR_PTR(-EINVAL); } } } else { /* being cautious here */ if (init_attr->qp_type != IB_QPT_XRC_TGT && init_attr->qp_type != MLX5_IB_QPT_REG_UMR) { pr_warn("%s: no PD for transport %s\n", __func__, ib_qp_type_str(init_attr->qp_type)); return ERR_PTR(-EINVAL); } dev = to_mdev(to_mxrcd(init_attr->xrcd)->ibxrcd.device); } if (init_attr->qp_type == IB_QPT_DRIVER) { struct mlx5_ib_create_qp ucmd; init_attr = &mlx_init_attr; memcpy(init_attr, verbs_init_attr, sizeof(*verbs_init_attr)); err = set_mlx_qp_type(dev, init_attr, &ucmd, udata); if (err) return ERR_PTR(err); if (init_attr->qp_type == MLX5_IB_QPT_DCI) { if (init_attr->cap.max_recv_wr || init_attr->cap.max_recv_sge) { mlx5_ib_dbg(dev, "DCI QP requires zero size receive queue\n"); return ERR_PTR(-EINVAL); } } else { return mlx5_ib_create_dct(pd, init_attr, &ucmd); } } switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: case IB_QPT_XRC_INI: if (!MLX5_CAP_GEN(dev->mdev, xrc)) { mlx5_ib_dbg(dev, "XRC not supported\n"); return ERR_PTR(-ENOSYS); } init_attr->recv_cq = NULL; if (init_attr->qp_type == IB_QPT_XRC_TGT) { xrcdn = to_mxrcd(init_attr->xrcd)->xrcdn; init_attr->send_cq = NULL; } /* fall through */ case IB_QPT_RAW_PACKET: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case MLX5_IB_QPT_REG_UMR: case MLX5_IB_QPT_DCI: qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); err = create_qp_common(dev, pd, init_attr, udata, qp); if (err) { mlx5_ib_dbg(dev, "create_qp_common failed\n"); kfree(qp); return ERR_PTR(err); } if (is_qp0(init_attr->qp_type)) qp->ibqp.qp_num = 0; else if (is_qp1(init_attr->qp_type)) qp->ibqp.qp_num = 1; else qp->ibqp.qp_num = qp->trans_qp.base.mqp.qpn; mlx5_ib_dbg(dev, "ib qpnum 0x%x, mlx qpn 0x%x, rcqn 0x%x, scqn 0x%x\n", qp->ibqp.qp_num, qp->trans_qp.base.mqp.qpn, init_attr->recv_cq ? to_mcq(init_attr->recv_cq)->mcq.cqn : -1, init_attr->send_cq ? to_mcq(init_attr->send_cq)->mcq.cqn : -1); qp->trans_qp.xrcdn = xrcdn; break; case IB_QPT_GSI: return mlx5_ib_gsi_create_qp(pd, init_attr); case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_MAX: default: mlx5_ib_dbg(dev, "unsupported qp type %d\n", init_attr->qp_type); /* Don't support raw QPs */ return ERR_PTR(-EINVAL); } if (verbs_init_attr->qp_type == IB_QPT_DRIVER) qp->qp_sub_type = init_attr->qp_type; return &qp->ibqp; } static int mlx5_ib_destroy_dct(struct mlx5_ib_qp *mqp) { struct mlx5_ib_dev *dev = to_mdev(mqp->ibqp.device); if (mqp->state == IB_QPS_RTR) { int err; err = mlx5_core_destroy_dct(dev->mdev, &mqp->dct.mdct); if (err) { mlx5_ib_warn(dev, "failed to destroy DCT %d\n", err); return err; } } kfree(mqp->dct.in); kfree(mqp); return 0; } int mlx5_ib_destroy_qp(struct ib_qp *qp) { struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_ib_qp *mqp = to_mqp(qp); if (unlikely(qp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_destroy_qp(qp); if (mqp->qp_sub_type == MLX5_IB_QPT_DCT) return mlx5_ib_destroy_dct(mqp); destroy_qp_common(dev, mqp); kfree(mqp); return 0; } static __be32 to_mlx5_access_flags(struct mlx5_ib_qp *qp, const struct ib_qp_attr *attr, int attr_mask) { u32 hw_access_flags = 0; u8 dest_rd_atomic; u32 access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) dest_rd_atomic = attr->max_dest_rd_atomic; else dest_rd_atomic = qp->trans_qp.resp_depth; if (attr_mask & IB_QP_ACCESS_FLAGS) access_flags = attr->qp_access_flags; else access_flags = qp->trans_qp.atomic_rd_en; if (!dest_rd_atomic) access_flags &= IB_ACCESS_REMOTE_WRITE; if (access_flags & IB_ACCESS_REMOTE_READ) hw_access_flags |= MLX5_QP_BIT_RRE; if (access_flags & IB_ACCESS_REMOTE_ATOMIC) hw_access_flags |= (MLX5_QP_BIT_RAE | MLX5_ATOMIC_MODE_CX); if (access_flags & IB_ACCESS_REMOTE_WRITE) hw_access_flags |= MLX5_QP_BIT_RWE; return cpu_to_be32(hw_access_flags); } enum { MLX5_PATH_FLAG_FL = 1 << 0, MLX5_PATH_FLAG_FREE_AR = 1 << 1, MLX5_PATH_FLAG_COUNTER = 1 << 2, }; static int ib_rate_to_mlx5(struct mlx5_ib_dev *dev, u8 rate) { if (rate == IB_RATE_PORT_CURRENT) return 0; if (rate < IB_RATE_2_5_GBPS || rate > IB_RATE_300_GBPS) return -EINVAL; while (rate != IB_RATE_PORT_CURRENT && !(1 << (rate + MLX5_STAT_RATE_OFFSET) & MLX5_CAP_GEN(dev->mdev, stat_rate_support))) --rate; return rate ? rate + MLX5_STAT_RATE_OFFSET : rate; } static int modify_raw_packet_eth_prio(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 sl) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.prio, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, prio, ((sl & 0x7) << 1)); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int modify_raw_packet_tx_affinity(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 tx_affinity) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.lag_tx_port_affinity, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, lag_tx_port_affinity, tx_affinity); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int mlx5_set_path(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct rdma_ah_attr *ah, struct mlx5_qp_path *path, u8 port, int attr_mask, u32 path_flags, const struct ib_qp_attr *attr, bool alt) { const struct ib_global_route *grh = rdma_ah_read_grh(ah); int err; enum ib_gid_type gid_type; u8 ah_flags = rdma_ah_get_ah_flags(ah); u8 sl = rdma_ah_get_sl(ah); if (attr_mask & IB_QP_PKEY_INDEX) path->pkey_index = cpu_to_be16(alt ? attr->alt_pkey_index : attr->pkey_index); if (ah_flags & IB_AH_GRH) { if (grh->sgid_index >= dev->mdev->port_caps[port - 1].gid_table_len) { pr_err("sgid_index (%u) too large. max is %d\n", grh->sgid_index, dev->mdev->port_caps[port - 1].gid_table_len); return -EINVAL; } } if (ah->type == RDMA_AH_ATTR_TYPE_ROCE) { if (!(ah_flags & IB_AH_GRH)) return -EINVAL; memcpy(path->rmac, ah->roce.dmac, sizeof(ah->roce.dmac)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC || qp->ibqp.qp_type == IB_QPT_XRC_INI || qp->ibqp.qp_type == IB_QPT_XRC_TGT) path->udp_sport = mlx5_get_roce_udp_sport(dev, ah->grh.sgid_attr); path->dci_cfi_prio_sl = (sl & 0x7) << 4; gid_type = ah->grh.sgid_attr->gid_type; if (gid_type == IB_GID_TYPE_ROCE_UDP_ENCAP) path->ecn_dscp = (grh->traffic_class >> 2) & 0x3f; } else { path->fl_free_ar = (path_flags & MLX5_PATH_FLAG_FL) ? 0x80 : 0; path->fl_free_ar |= (path_flags & MLX5_PATH_FLAG_FREE_AR) ? 0x40 : 0; path->rlid = cpu_to_be16(rdma_ah_get_dlid(ah)); path->grh_mlid = rdma_ah_get_path_bits(ah) & 0x7f; if (ah_flags & IB_AH_GRH) path->grh_mlid |= 1 << 7; path->dci_cfi_prio_sl = sl & 0xf; } if (ah_flags & IB_AH_GRH) { path->mgid_index = grh->sgid_index; path->hop_limit = grh->hop_limit; path->tclass_flowlabel = cpu_to_be32((grh->traffic_class << 20) | (grh->flow_label)); memcpy(path->rgid, grh->dgid.raw, 16); } err = ib_rate_to_mlx5(dev, rdma_ah_get_static_rate(ah)); if (err < 0) return err; path->static_rate = err; path->port = port; if (attr_mask & IB_QP_TIMEOUT) path->ackto_lt = (alt ? attr->alt_timeout : attr->timeout) << 3; if ((qp->ibqp.qp_type == IB_QPT_RAW_PACKET) && qp->sq.wqe_cnt) return modify_raw_packet_eth_prio(dev->mdev, &qp->raw_packet_qp.sq, sl & 0xf); return 0; } static enum mlx5_qp_optpar opt_mask[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE][MLX5_QP_ST_MAX] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_PRI_PORT, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_XRC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, }, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_RNR_TIMEOUT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, }, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_SRQN | MLX5_QP_OPTPAR_CQN_RCV, }, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE, [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RRE, }, }, }; static int ib_nr_to_mlx5_nr(int ib_mask) { switch (ib_mask) { case IB_QP_STATE: return 0; case IB_QP_CUR_STATE: return 0; case IB_QP_EN_SQD_ASYNC_NOTIFY: return 0; case IB_QP_ACCESS_FLAGS: return MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PKEY_INDEX: return MLX5_QP_OPTPAR_PKEY_INDEX; case IB_QP_PORT: return MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_QKEY: return MLX5_QP_OPTPAR_Q_KEY; case IB_QP_AV: return MLX5_QP_OPTPAR_PRIMARY_ADDR_PATH | MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_PATH_MTU: return 0; case IB_QP_TIMEOUT: return MLX5_QP_OPTPAR_ACK_TIMEOUT; case IB_QP_RETRY_CNT: return MLX5_QP_OPTPAR_RETRY_COUNT; case IB_QP_RNR_RETRY: return MLX5_QP_OPTPAR_RNR_RETRY; case IB_QP_RQ_PSN: return 0; case IB_QP_MAX_QP_RD_ATOMIC: return MLX5_QP_OPTPAR_SRA_MAX; case IB_QP_ALT_PATH: return MLX5_QP_OPTPAR_ALT_ADDR_PATH; case IB_QP_MIN_RNR_TIMER: return MLX5_QP_OPTPAR_RNR_TIMEOUT; case IB_QP_SQ_PSN: return 0; case IB_QP_MAX_DEST_RD_ATOMIC: return MLX5_QP_OPTPAR_RRA_MAX | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PATH_MIG_STATE: return MLX5_QP_OPTPAR_PM_STATE; case IB_QP_CAP: return 0; case IB_QP_DEST_QPN: return 0; } return 0; } static int ib_mask_to_mlx5_opt(int ib_mask) { int result = 0; int i; for (i = 0; i < 8 * sizeof(int); i++) { if ((1 << i) & ib_mask) result |= ib_nr_to_mlx5_nr(1 << i); } return result; } static int modify_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { void *in; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_rq_in, in, rq_state, rq->state); rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); MLX5_SET(rqc, rqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, raw_qp_param->rq_q_ctr_id); } else pr_info_once("%s: RAW PACKET QP counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rq->base.mqp.qpn, in, inlen); if (err) goto out; rq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp_sq(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { struct mlx5_ib_qp *ibqp = sq->base.container_mibqp; struct mlx5_rate_limit old_rl = ibqp->rl; struct mlx5_rate_limit new_rl = old_rl; bool new_rate_added = false; u16 rl_index = 0; void *in; void *sqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_sq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_sq_in, in, sq_state, sq->state); sqc = MLX5_ADDR_OF(modify_sq_in, in, ctx); MLX5_SET(sqc, sqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_RATE_LIMIT) { if (new_state != MLX5_SQC_STATE_RDY) pr_warn("%s: Rate limit can only be changed when SQ is moving to RDY\n", __func__); else new_rl = raw_qp_param->rl; } if (!mlx5_rl_are_equal(&old_rl, &new_rl)) { if (new_rl.rate) { err = mlx5_rl_add_rate(dev, &rl_index, &new_rl); if (err) { pr_err("Failed configuring rate limit(err %d): \ rate %u, max_burst_sz %u, typical_pkt_sz %u\n", err, new_rl.rate, new_rl.max_burst_sz, new_rl.typical_pkt_sz); goto out; } new_rate_added = true; } MLX5_SET64(modify_sq_in, in, modify_bitmask, 1); /* index 0 means no limit */ MLX5_SET(sqc, sqc, packet_pacing_rate_limit_index, rl_index); } err = mlx5_core_modify_sq(dev, sq->base.mqp.qpn, in, inlen); if (err) { /* Remove new rate from table if failed */ if (new_rate_added) mlx5_rl_remove_rate(dev, &new_rl); goto out; } /* Only remove the old rate after new rate was set */ if ((old_rl.rate && !mlx5_rl_are_equal(&old_rl, &new_rl)) || (new_state != MLX5_SQC_STATE_RDY)) mlx5_rl_remove_rate(dev, &old_rl); ibqp->rl = new_rl; sq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 tx_affinity) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; int modify_rq = !!qp->rq.wqe_cnt; int modify_sq = !!qp->sq.wqe_cnt; int rq_state; int sq_state; int err; switch (raw_qp_param->operation) { case MLX5_CMD_OP_RST2INIT_QP: rq_state = MLX5_RQC_STATE_RDY; sq_state = MLX5_SQC_STATE_RDY; break; case MLX5_CMD_OP_2ERR_QP: rq_state = MLX5_RQC_STATE_ERR; sq_state = MLX5_SQC_STATE_ERR; break; case MLX5_CMD_OP_2RST_QP: rq_state = MLX5_RQC_STATE_RST; sq_state = MLX5_SQC_STATE_RST; break; case MLX5_CMD_OP_RTR2RTS_QP: case MLX5_CMD_OP_RTS2RTS_QP: if (raw_qp_param->set_mask == MLX5_RAW_QP_RATE_LIMIT) { modify_rq = 0; sq_state = sq->state; } else { return raw_qp_param->set_mask ? -EINVAL : 0; } break; case MLX5_CMD_OP_INIT2INIT_QP: case MLX5_CMD_OP_INIT2RTR_QP: if (raw_qp_param->set_mask) return -EINVAL; else return 0; default: WARN_ON(1); return -EINVAL; } if (modify_rq) { err = modify_raw_packet_qp_rq(dev, rq, rq_state, raw_qp_param); if (err) return err; } if (modify_sq) { if (tx_affinity) { err = modify_raw_packet_tx_affinity(dev->mdev, sq, tx_affinity); if (err) return err; } return modify_raw_packet_qp_sq(dev->mdev, sq, sq_state, raw_qp_param); } return 0; } static int __mlx5_ib_modify_qp(struct ib_qp *ibqp, const struct ib_qp_attr *attr, int attr_mask, enum ib_qp_state cur_state, enum ib_qp_state new_state, const struct mlx5_ib_modify_qp *ucmd) { static const u16 optab[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE] = { [MLX5_QP_STATE_RST] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_RST2INIT_QP, }, [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_INIT2INIT_QP, [MLX5_QP_STATE_RTR] = MLX5_CMD_OP_INIT2RTR_QP, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTR2RTS_QP, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTS2RTS_QP, }, [MLX5_QP_STATE_SQD] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_SQERR2RTS_QP, }, [MLX5_QP_STATE_ERR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, } }; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_qp_base *base = &qp->trans_qp.base; struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_qp_context *context; struct mlx5_ib_pd *pd; struct mlx5_ib_port *mibport = NULL; enum mlx5_qp_state mlx5_cur, mlx5_new; enum mlx5_qp_optpar optpar; int mlx5_st; int err; u16 op; u8 tx_affinity = 0; mlx5_st = to_mlx5_st(ibqp->qp_type == IB_QPT_DRIVER ? qp->qp_sub_type : ibqp->qp_type); if (mlx5_st < 0) return -EINVAL; context = kzalloc(sizeof(*context), GFP_KERNEL); if (!context) return -ENOMEM; context->flags = cpu_to_be32(mlx5_st << 16); if (!(attr_mask & IB_QP_PATH_MIG_STATE)) { context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); } else { switch (attr->path_mig_state) { case IB_MIG_MIGRATED: context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); break; case IB_MIG_REARM: context->flags |= cpu_to_be32(MLX5_QP_PM_REARM << 11); break; case IB_MIG_ARMED: context->flags |= cpu_to_be32(MLX5_QP_PM_ARMED << 11); break; } } if ((cur_state == IB_QPS_RESET) && (new_state == IB_QPS_INIT)) { if ((ibqp->qp_type == IB_QPT_RC) || (ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_SQPN_QP1)) || (ibqp->qp_type == IB_QPT_UC) || (ibqp->qp_type == IB_QPT_RAW_PACKET) || (ibqp->qp_type == IB_QPT_XRC_INI) || (ibqp->qp_type == IB_QPT_XRC_TGT)) { if (mlx5_lag_is_active(dev->mdev)) { u8 p = mlx5_core_native_port_num(dev->mdev); tx_affinity = (unsigned int)atomic_add_return(1, &dev->roce[p].next_port) % MLX5_MAX_PORTS + 1; context->flags |= cpu_to_be32(tx_affinity << 24); } } } if (is_sqp(ibqp->qp_type)) { context->mtu_msgmax = (IB_MTU_256 << 5) | 8; } else if ((ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_UNDERLAY)) || ibqp->qp_type == MLX5_IB_QPT_REG_UMR) { context->mtu_msgmax = (IB_MTU_4096 << 5) | 12; } else if (attr_mask & IB_QP_PATH_MTU) { if (attr->path_mtu < IB_MTU_256 || attr->path_mtu > IB_MTU_4096) { mlx5_ib_warn(dev, "invalid mtu %d\n", attr->path_mtu); err = -EINVAL; goto out; } context->mtu_msgmax = (attr->path_mtu << 5) | (u8)MLX5_CAP_GEN(dev->mdev, log_max_msg); } if (attr_mask & IB_QP_DEST_QPN) context->log_pg_sz_remote_qpn = cpu_to_be32(attr->dest_qp_num); if (attr_mask & IB_QP_PKEY_INDEX) context->pri_path.pkey_index = cpu_to_be16(attr->pkey_index); /* todo implement counter_index functionality */ if (is_sqp(ibqp->qp_type)) context->pri_path.port = qp->port; if (attr_mask & IB_QP_PORT) context->pri_path.port = attr->port_num; if (attr_mask & IB_QP_AV) { err = mlx5_set_path(dev, qp, &attr->ah_attr, &context->pri_path, attr_mask & IB_QP_PORT ? attr->port_num : qp->port, attr_mask, 0, attr, false); if (err) goto out; } if (attr_mask & IB_QP_TIMEOUT) context->pri_path.ackto_lt |= attr->timeout << 3; if (attr_mask & IB_QP_ALT_PATH) { err = mlx5_set_path(dev, qp, &attr->alt_ah_attr, &context->alt_path, attr->alt_port_num, attr_mask | IB_QP_PKEY_INDEX | IB_QP_TIMEOUT, 0, attr, true); if (err) goto out; } pd = get_pd(qp); get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); context->flags_pd = cpu_to_be32(pd ? pd->pdn : to_mpd(dev->devr.p0)->pdn); context->cqn_send = send_cq ? cpu_to_be32(send_cq->mcq.cqn) : 0; context->cqn_recv = recv_cq ? cpu_to_be32(recv_cq->mcq.cqn) : 0; context->params1 = cpu_to_be32(MLX5_IB_ACK_REQ_FREQ << 28); if (attr_mask & IB_QP_RNR_RETRY) context->params1 |= cpu_to_be32(attr->rnr_retry << 13); if (attr_mask & IB_QP_RETRY_CNT) context->params1 |= cpu_to_be32(attr->retry_cnt << 16); if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) { if (attr->max_rd_atomic) context->params1 |= cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21); } if (attr_mask & IB_QP_SQ_PSN) context->next_send_psn = cpu_to_be32(attr->sq_psn); if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) { if (attr->max_dest_rd_atomic) context->params2 |= cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21); } if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC)) context->params2 |= to_mlx5_access_flags(qp, attr, attr_mask); if (attr_mask & IB_QP_MIN_RNR_TIMER) context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24); if (attr_mask & IB_QP_RQ_PSN) context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn); if (attr_mask & IB_QP_QKEY) context->qkey = cpu_to_be32(attr->qkey); if (qp->rq.wqe_cnt && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->db_rec_addr = cpu_to_be64(qp->db.dma); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { u8 port_num = (attr_mask & IB_QP_PORT ? attr->port_num : qp->port) - 1; /* Underlay port should be used - index 0 function per port */ if (qp->flags & MLX5_IB_QP_UNDERLAY) port_num = 0; mibport = &dev->port[port_num]; context->qp_counter_set_usr_page |= cpu_to_be32((u32)(mibport->cnts.set_id) << 24); } if (!ibqp->uobject && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->sq_crq_size |= cpu_to_be16(1 << 4); if (qp->flags & MLX5_IB_QP_SQPN_QP1) context->deth_sqpn = cpu_to_be32(1); mlx5_cur = to_mlx5_state(cur_state); mlx5_new = to_mlx5_state(new_state); if (mlx5_cur >= MLX5_QP_NUM_STATE || mlx5_new >= MLX5_QP_NUM_STATE || !optab[mlx5_cur][mlx5_new]) { err = -EINVAL; goto out; } op = optab[mlx5_cur][mlx5_new]; optpar = ib_mask_to_mlx5_opt(attr_mask); optpar &= opt_mask[mlx5_cur][mlx5_new][mlx5_st]; if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { struct mlx5_modify_raw_qp_param raw_qp_param = {}; raw_qp_param.operation = op; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { raw_qp_param.rq_q_ctr_id = mibport->cnts.set_id; raw_qp_param.set_mask |= MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID; } if (attr_mask & IB_QP_RATE_LIMIT) { raw_qp_param.rl.rate = attr->rate_limit; if (ucmd->burst_info.max_burst_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_burst_bound)) { raw_qp_param.rl.max_burst_sz = ucmd->burst_info.max_burst_sz; } else { err = -EINVAL; goto out; } } if (ucmd->burst_info.typical_pkt_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_typical_size)) { raw_qp_param.rl.typical_pkt_sz = ucmd->burst_info.typical_pkt_sz; } else { err = -EINVAL; goto out; } } raw_qp_param.set_mask |= MLX5_RAW_QP_RATE_LIMIT; } err = modify_raw_packet_qp(dev, qp, &raw_qp_param, tx_affinity); } else { err = mlx5_core_qp_modify(dev->mdev, op, optpar, context, &base->mqp); } if (err) goto out; qp->state = new_state; if (attr_mask & IB_QP_ACCESS_FLAGS) qp->trans_qp.atomic_rd_en = attr->qp_access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) qp->trans_qp.resp_depth = attr->max_dest_rd_atomic; if (attr_mask & IB_QP_PORT) qp->port = attr->port_num; if (attr_mask & IB_QP_ALT_PATH) qp->trans_qp.alt_port = attr->alt_port_num; /* * If we moved a kernel QP to RESET, clean up all old CQ * entries and reinitialize the QP. */ if (new_state == IB_QPS_RESET && !ibqp->uobject && ibqp->qp_type != IB_QPT_XRC_TGT) { mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, ibqp->srq ? to_msrq(ibqp->srq) : NULL); if (send_cq != recv_cq) mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); qp->rq.head = 0; qp->rq.tail = 0; qp->sq.head = 0; qp->sq.tail = 0; qp->sq.cur_post = 0; qp->sq.last_poll = 0; qp->db.db[MLX5_RCV_DBR] = 0; qp->db.db[MLX5_SND_DBR] = 0; } out: kfree(context); return err; } static inline bool is_valid_mask(int mask, int req, int opt) { if ((mask & req) != req) return false; if (mask & ~(req | opt)) return false; return true; } /* check valid transition for driver QP types * for now the only QP type that this function supports is DCI */ static bool modify_dci_qp_is_ok(enum ib_qp_state cur_state, enum ib_qp_state new_state, enum ib_qp_attr_mask attr_mask) { int req = IB_QP_STATE; int opt = 0; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { req |= IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_INIT) { opt = IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { req |= IB_QP_PATH_MTU; opt = IB_QP_PKEY_INDEX; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTR && new_state == IB_QPS_RTS) { req |= IB_QP_TIMEOUT | IB_QP_RETRY_CNT | IB_QP_RNR_RETRY | IB_QP_MAX_QP_RD_ATOMIC | IB_QP_SQ_PSN; opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTS && new_state == IB_QPS_RTS) { opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state != IB_QPS_RESET && new_state == IB_QPS_ERR) { return is_valid_mask(attr_mask, req, opt); } return false; } /* mlx5_ib_modify_dct: modify a DCT QP * valid transitions are: * RESET to INIT: must set access_flags, pkey_index and port * INIT to RTR : must set min_rnr_timer, tclass, flow_label, * mtu, gid_index and hop_limit * Other transitions and attributes are illegal */ static int mlx5_ib_modify_dct(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_dev *dev = to_mdev(ibqp->device); enum ib_qp_state cur_state, new_state; int err = 0; int required = IB_QP_STATE; void *dctc; if (!(attr_mask & IB_QP_STATE)) return -EINVAL; cur_state = qp->state; new_state = attr->qp_state; dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { required |= IB_QP_ACCESS_FLAGS | IB_QP_PKEY_INDEX | IB_QP_PORT; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; if (attr->port_num == 0 || attr->port_num > MLX5_CAP_GEN(dev->mdev, num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); return -EINVAL; } if (attr->qp_access_flags & IB_ACCESS_REMOTE_READ) MLX5_SET(dctc, dctc, rre, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_WRITE) MLX5_SET(dctc, dctc, rwe, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_ATOMIC) { if (!mlx5_ib_dc_atomic_is_supported(dev)) return -EOPNOTSUPP; MLX5_SET(dctc, dctc, rae, 1); MLX5_SET(dctc, dctc, atomic_mode, MLX5_ATOMIC_MODE_DCT_CX); } MLX5_SET(dctc, dctc, pkey_index, attr->pkey_index); MLX5_SET(dctc, dctc, port, attr->port_num); MLX5_SET(dctc, dctc, counter_set_id, dev->port[attr->port_num - 1].cnts.set_id); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { struct mlx5_ib_modify_qp_resp resp = {}; u32 min_resp_len = offsetof(typeof(resp), dctn) + sizeof(resp.dctn); if (udata->outlen < min_resp_len) return -EINVAL; resp.response_length = min_resp_len; required |= IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; MLX5_SET(dctc, dctc, min_rnr_nak, attr->min_rnr_timer); MLX5_SET(dctc, dctc, tclass, attr->ah_attr.grh.traffic_class); MLX5_SET(dctc, dctc, flow_label, attr->ah_attr.grh.flow_label); MLX5_SET(dctc, dctc, mtu, attr->path_mtu); MLX5_SET(dctc, dctc, my_addr_index, attr->ah_attr.grh.sgid_index); MLX5_SET(dctc, dctc, hop_limit, attr->ah_attr.grh.hop_limit); err = mlx5_core_create_dct(dev->mdev, &qp->dct.mdct, qp->dct.in, MLX5_ST_SZ_BYTES(create_dct_in)); if (err) return err; resp.dctn = qp->dct.mdct.mqp.qpn; err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) { mlx5_core_destroy_dct(dev->mdev, &qp->dct.mdct); return err; } } else { mlx5_ib_warn(dev, "Modify DCT: Invalid transition from %d to %d\n", cur_state, new_state); return -EINVAL; } if (err) qp->state = IB_QPS_ERR; else qp->state = new_state; return err; } int mlx5_ib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_modify_qp ucmd = {}; enum ib_qp_type qp_type; enum ib_qp_state cur_state, new_state; size_t required_cmd_sz; int err = -EINVAL; int port; enum rdma_link_layer ll = IB_LINK_LAYER_UNSPECIFIED; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (udata && udata->inlen) { required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(udata->inlen, sizeof(ucmd)))) return -EFAULT; if (ucmd.comp_mask || memchr_inv(&ucmd.reserved, 0, sizeof(ucmd.reserved)) || memchr_inv(&ucmd.burst_info.reserved, 0, sizeof(ucmd.burst_info.reserved))) return -EOPNOTSUPP; } if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_modify_qp(ibqp, attr, attr_mask); if (ibqp->qp_type == IB_QPT_DRIVER) qp_type = qp->qp_sub_type; else qp_type = (unlikely(ibqp->qp_type == MLX5_IB_QPT_HW_GSI)) ? IB_QPT_GSI : ibqp->qp_type; if (qp_type == MLX5_IB_QPT_DCT) return mlx5_ib_modify_dct(ibqp, attr, attr_mask, udata); mutex_lock(&qp->mutex); cur_state = attr_mask & IB_QP_CUR_STATE ? attr->cur_qp_state : qp->state; new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state; if (!(cur_state == new_state && cur_state == IB_QPS_RESET)) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; ll = dev->ib_dev.get_link_layer(&dev->ib_dev, port); } if (qp->flags & MLX5_IB_QP_UNDERLAY) { if (attr_mask & ~(IB_QP_STATE | IB_QP_CUR_STATE)) { mlx5_ib_dbg(dev, "invalid attr_mask 0x%x when underlay QP is used\n", attr_mask); goto out; } } else if (qp_type != MLX5_IB_QPT_REG_UMR && qp_type != MLX5_IB_QPT_DCI && !ib_modify_qp_is_ok(cur_state, new_state, qp_type, attr_mask, ll)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, ibqp->qp_type, attr_mask); goto out; } else if (qp_type == MLX5_IB_QPT_DCI && !modify_dci_qp_is_ok(cur_state, new_state, attr_mask)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, qp_type, attr_mask); goto out; } if ((attr_mask & IB_QP_PORT) && (attr->port_num == 0 || attr->port_num > dev->num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); goto out; } if (attr_mask & IB_QP_PKEY_INDEX) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; if (attr->pkey_index >= dev->mdev->port_caps[port - 1].pkey_table_len) { mlx5_ib_dbg(dev, "invalid pkey index %d\n", attr->pkey_index); goto out; } } if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC && attr->max_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_res_qp))) { mlx5_ib_dbg(dev, "invalid max_rd_atomic value %d\n", attr->max_rd_atomic); goto out; } if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC && attr->max_dest_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_req_qp))) { mlx5_ib_dbg(dev, "invalid max_dest_rd_atomic value %d\n", attr->max_dest_rd_atomic); goto out; } if (cur_state == new_state && cur_state == IB_QPS_RESET) { err = 0; goto out; } err = __mlx5_ib_modify_qp(ibqp, attr, attr_mask, cur_state, new_state, &ucmd); out: mutex_unlock(&qp->mutex); return err; } static int mlx5_wq_overflow(struct mlx5_ib_wq *wq, int nreq, struct ib_cq *ib_cq) { struct mlx5_ib_cq *cq; unsigned cur; cur = wq->head - wq->tail; if (likely(cur + nreq < wq->max_post)) return 0; cq = to_mcq(ib_cq); spin_lock(&cq->lock); cur = wq->head - wq->tail; spin_unlock(&cq->lock); return cur + nreq >= wq->max_post; } static __always_inline void set_raddr_seg(struct mlx5_wqe_raddr_seg *rseg, u64 remote_addr, u32 rkey) { rseg->raddr = cpu_to_be64(remote_addr); rseg->rkey = cpu_to_be32(rkey); rseg->reserved = 0; } static void *set_eth_seg(struct mlx5_wqe_eth_seg *eseg, const struct ib_send_wr *wr, void *qend, struct mlx5_ib_qp *qp, int *size) { void *seg = eseg; memset(eseg, 0, sizeof(struct mlx5_wqe_eth_seg)); if (wr->send_flags & IB_SEND_IP_CSUM) eseg->cs_flags = MLX5_ETH_WQE_L3_CSUM | MLX5_ETH_WQE_L4_CSUM; seg += sizeof(struct mlx5_wqe_eth_seg); *size += sizeof(struct mlx5_wqe_eth_seg) / 16; if (wr->opcode == IB_WR_LSO) { struct ib_ud_wr *ud_wr = container_of(wr, struct ib_ud_wr, wr); int size_of_inl_hdr_start = sizeof(eseg->inline_hdr.start); u64 left, leftlen, copysz; void *pdata = ud_wr->header; left = ud_wr->hlen; eseg->mss = cpu_to_be16(ud_wr->mss); eseg->inline_hdr.sz = cpu_to_be16(left); /* * check if there is space till the end of queue, if yes, * copy all in one shot, otherwise copy till the end of queue, * rollback and than the copy the left */ leftlen = qend - (void *)eseg->inline_hdr.start; copysz = min_t(u64, leftlen, left); memcpy(seg - size_of_inl_hdr_start, pdata, copysz); if (likely(copysz > size_of_inl_hdr_start)) { seg += ALIGN(copysz - size_of_inl_hdr_start, 16); *size += ALIGN(copysz - size_of_inl_hdr_start, 16) / 16; } if (unlikely(copysz < left)) { /* the last wqe in the queue */ seg = mlx5_get_send_wqe(qp, 0); left -= copysz; pdata += copysz; memcpy(seg, pdata, left); seg += ALIGN(left, 16); *size += ALIGN(left, 16) / 16; } } return seg; } static void set_datagram_seg(struct mlx5_wqe_datagram_seg *dseg, const struct ib_send_wr *wr) { memcpy(&dseg->av, &to_mah(ud_wr(wr)->ah)->av, sizeof(struct mlx5_av)); dseg->av.dqp_dct = cpu_to_be32(ud_wr(wr)->remote_qpn | MLX5_EXTENDED_UD_AV); dseg->av.key.qkey.qkey = cpu_to_be32(ud_wr(wr)->remote_qkey); } static void set_data_ptr_seg(struct mlx5_wqe_data_seg *dseg, struct ib_sge *sg) { dseg->byte_count = cpu_to_be32(sg->length); dseg->lkey = cpu_to_be32(sg->lkey); dseg->addr = cpu_to_be64(sg->addr); } static u64 get_xlt_octo(u64 bytes) { return ALIGN(bytes, MLX5_IB_UMR_XLT_ALIGNMENT) / MLX5_IB_UMR_OCTOWORD; } static __be64 frwr_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_A | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 sig_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_SIGERR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE | MLX5_MKEY_MASK_BSF_EN; return cpu_to_be64(result); } static void set_reg_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr, struct mlx5_ib_mr *mr, bool umr_inline) { int size = mr->ndescs * mr->desc_size; memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_UMR_CHECK_NOT_FREE; if (umr_inline) umr->flags |= MLX5_UMR_INLINE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->mkey_mask = frwr_mkey_mask(); } static void set_linv_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr) { memset(umr, 0, sizeof(*umr)); umr->mkey_mask = cpu_to_be64(MLX5_MKEY_MASK_FREE); umr->flags = MLX5_UMR_INLINE; } static __be64 get_umr_enable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_disable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_update_translation_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR; return cpu_to_be64(result); } static __be64 get_umr_update_access_mask(int atomic) { u64 result; result = MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW; if (atomic) result |= MLX5_MKEY_MASK_A; return cpu_to_be64(result); } static __be64 get_umr_update_pd_mask(void) { u64 result; result = MLX5_MKEY_MASK_PD; return cpu_to_be64(result); } static int umr_check_mkey_mask(struct mlx5_ib_dev *dev, u64 mask) { if ((mask & MLX5_MKEY_MASK_PAGE_SIZE && MLX5_CAP_GEN(dev->mdev, umr_modify_entity_size_disabled)) || (mask & MLX5_MKEY_MASK_A && MLX5_CAP_GEN(dev->mdev, umr_modify_atomic_disabled))) return -EPERM; return 0; } static int set_reg_umr_segment(struct mlx5_ib_dev *dev, struct mlx5_wqe_umr_ctrl_seg *umr, const struct ib_send_wr *wr, int atomic) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(umr, 0, sizeof(*umr)); if (wr->send_flags & MLX5_IB_SEND_UMR_FAIL_IF_FREE) umr->flags = MLX5_UMR_CHECK_FREE; /* fail if free */ else umr->flags = MLX5_UMR_CHECK_NOT_FREE; /* fail if not free */ umr->xlt_octowords = cpu_to_be16(get_xlt_octo(umrwr->xlt_size)); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_XLT) { u64 offset = get_xlt_octo(umrwr->offset); umr->xlt_offset = cpu_to_be16(offset & 0xffff); umr->xlt_offset_47_16 = cpu_to_be32(offset >> 16); umr->flags |= MLX5_UMR_TRANSLATION_OFFSET_EN; } if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION) umr->mkey_mask |= get_umr_update_translation_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS) { umr->mkey_mask |= get_umr_update_access_mask(atomic); umr->mkey_mask |= get_umr_update_pd_mask(); } if (wr->send_flags & MLX5_IB_SEND_UMR_ENABLE_MR) umr->mkey_mask |= get_umr_enable_mr_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) umr->mkey_mask |= get_umr_disable_mr_mask(); if (!wr->num_sge) umr->flags |= MLX5_UMR_INLINE; return umr_check_mkey_mask(dev, be64_to_cpu(umr->mkey_mask)); } static u8 get_umr_flags(int acc) { return (acc & IB_ACCESS_REMOTE_ATOMIC ? MLX5_PERM_ATOMIC : 0) | (acc & IB_ACCESS_REMOTE_WRITE ? MLX5_PERM_REMOTE_WRITE : 0) | (acc & IB_ACCESS_REMOTE_READ ? MLX5_PERM_REMOTE_READ : 0) | (acc & IB_ACCESS_LOCAL_WRITE ? MLX5_PERM_LOCAL_WRITE : 0) | MLX5_PERM_LOCAL_READ | MLX5_PERM_UMR_EN; } static void set_reg_mkey_seg(struct mlx5_mkey_seg *seg, struct mlx5_ib_mr *mr, u32 key, int access) { int ndescs = ALIGN(mr->ndescs, 8) >> 1; memset(seg, 0, sizeof(*seg)); if (mr->access_mode == MLX5_MKC_ACCESS_MODE_MTT) seg->log2_page_size = ilog2(mr->ibmr.page_size); else if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS) /* KLMs take twice the size of MTTs */ ndescs *= 2; seg->flags = get_umr_flags(access) | mr->access_mode; seg->qpn_mkey7_0 = cpu_to_be32((key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL); seg->start_addr = cpu_to_be64(mr->ibmr.iova); seg->len = cpu_to_be64(mr->ibmr.length); seg->xlt_oct_size = cpu_to_be32(ndescs); } static void set_linv_mkey_seg(struct mlx5_mkey_seg *seg) { memset(seg, 0, sizeof(*seg)); seg->status = MLX5_MKEY_STATUS_FREE; } static void set_reg_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_send_wr *wr) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(seg, 0, sizeof(*seg)); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) seg->status = MLX5_MKEY_STATUS_FREE; seg->flags = convert_access(umrwr->access_flags); if (umrwr->pd) seg->flags_pd = cpu_to_be32(to_mpd(umrwr->pd)->pdn); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION && !umrwr->length) seg->flags_pd |= cpu_to_be32(MLX5_MKEY_LEN64); seg->start_addr = cpu_to_be64(umrwr->virt_addr); seg->len = cpu_to_be64(umrwr->length); seg->log2_page_size = umrwr->page_shift; seg->qpn_mkey7_0 = cpu_to_be32(0xffffff00 | mlx5_mkey_variant(umrwr->mkey)); } static void set_reg_data_seg(struct mlx5_wqe_data_seg *dseg, struct mlx5_ib_mr *mr, struct mlx5_ib_pd *pd) { int bcount = mr->desc_size * mr->ndescs; dseg->addr = cpu_to_be64(mr->desc_map); dseg->byte_count = cpu_to_be32(ALIGN(bcount, 64)); dseg->lkey = cpu_to_be32(pd->ibpd.local_dma_lkey); } static void set_reg_umr_inline_seg(void *seg, struct mlx5_ib_qp *qp, struct mlx5_ib_mr *mr, int mr_list_size) { void *qend = qp->sq.qend; void *addr = mr->descs; int copy; if (unlikely(seg + mr_list_size > qend)) { copy = qend - seg; memcpy(seg, addr, copy); addr += copy; mr_list_size -= copy; seg = mlx5_get_send_wqe(qp, 0); } memcpy(seg, addr, mr_list_size); seg += mr_list_size; } static __be32 send_ieth(const struct ib_send_wr *wr) { switch (wr->opcode) { case IB_WR_SEND_WITH_IMM: case IB_WR_RDMA_WRITE_WITH_IMM: return wr->ex.imm_data; case IB_WR_SEND_WITH_INV: return cpu_to_be32(wr->ex.invalidate_rkey); default: return 0; } } static u8 calc_sig(void *wqe, int size) { u8 *p = wqe; u8 res = 0; int i; for (i = 0; i < size; i++) res ^= p[i]; return ~res; } static u8 wq_sig(void *wqe) { return calc_sig(wqe, (*((u8 *)wqe + 8) & 0x3f) << 4); } static int set_data_inl_seg(struct mlx5_ib_qp *qp, const struct ib_send_wr *wr, void *wqe, int *sz) { struct mlx5_wqe_inline_seg *seg; void *qend = qp->sq.qend; void *addr; int inl = 0; int copy; int len; int i; seg = wqe; wqe += sizeof(*seg); for (i = 0; i < wr->num_sge; i++) { addr = (void *)(unsigned long)(wr->sg_list[i].addr); len = wr->sg_list[i].length; inl += len; if (unlikely(inl > qp->max_inline_data)) return -ENOMEM; if (unlikely(wqe + len > qend)) { copy = qend - wqe; memcpy(wqe, addr, copy); addr += copy; len -= copy; wqe = mlx5_get_send_wqe(qp, 0); } memcpy(wqe, addr, len); wqe += len; } seg->byte_count = cpu_to_be32(inl | MLX5_INLINE_SEG); *sz = ALIGN(inl + sizeof(seg->byte_count), 16) / 16; return 0; } static u16 prot_field_size(enum ib_signature_type type) { switch (type) { case IB_SIG_TYPE_T10_DIF: return MLX5_DIF_SIZE; default: return 0; } } static u8 bs_selector(int block_size) { switch (block_size) { case 512: return 0x1; case 520: return 0x2; case 4096: return 0x3; case 4160: return 0x4; case 1073741824: return 0x5; default: return 0; } } static void mlx5_fill_inl_bsf(struct ib_sig_domain *domain, struct mlx5_bsf_inl *inl) { /* Valid inline section and allow BSF refresh */ inl->vld_refresh = cpu_to_be16(MLX5_BSF_INL_VALID | MLX5_BSF_REFRESH_DIF); inl->dif_apptag = cpu_to_be16(domain->sig.dif.app_tag); inl->dif_reftag = cpu_to_be32(domain->sig.dif.ref_tag); /* repeating block */ inl->rp_inv_seed = MLX5_BSF_REPEAT_BLOCK; inl->sig_type = domain->sig.dif.bg_type == IB_T10DIF_CRC ? MLX5_DIF_CRC : MLX5_DIF_IPCS; if (domain->sig.dif.ref_remap) inl->dif_inc_ref_guard_check |= MLX5_BSF_INC_REFTAG; if (domain->sig.dif.app_escape) { if (domain->sig.dif.ref_escape) inl->dif_inc_ref_guard_check |= MLX5_BSF_APPREF_ESCAPE; else inl->dif_inc_ref_guard_check |= MLX5_BSF_APPTAG_ESCAPE; } inl->dif_app_bitmask_check = cpu_to_be16(domain->sig.dif.apptag_check_mask); } static int mlx5_set_bsf(struct ib_mr *sig_mr, struct ib_sig_attrs *sig_attrs, struct mlx5_bsf *bsf, u32 data_size) { struct mlx5_core_sig_ctx *msig = to_mmr(sig_mr)->sig; struct mlx5_bsf_basic *basic = &bsf->basic; struct ib_sig_domain *mem = &sig_attrs->mem; struct ib_sig_domain *wire = &sig_attrs->wire; memset(bsf, 0, sizeof(*bsf)); /* Basic + Extended + Inline */ basic->bsf_size_sbs = 1 << 7; /* Input domain check byte mask */ basic->check_byte_mask = sig_attrs->check_mask; basic->raw_data_size = cpu_to_be32(data_size); /* Memory domain */ switch (sig_attrs->mem.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: basic->mem.bs_selector = bs_selector(mem->sig.dif.pi_interval); basic->m_bfs_psv = cpu_to_be32(msig->psv_memory.psv_idx); mlx5_fill_inl_bsf(mem, &bsf->m_inl); break; default: return -EINVAL; } /* Wire domain */ switch (sig_attrs->wire.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: if (mem->sig.dif.pi_interval == wire->sig.dif.pi_interval && mem->sig_type == wire->sig_type) { /* Same block structure */ basic->bsf_size_sbs |= 1 << 4; if (mem->sig.dif.bg_type == wire->sig.dif.bg_type) basic->wire.copy_byte_mask |= MLX5_CPY_GRD_MASK; if (mem->sig.dif.app_tag == wire->sig.dif.app_tag) basic->wire.copy_byte_mask |= MLX5_CPY_APP_MASK; if (mem->sig.dif.ref_tag == wire->sig.dif.ref_tag) basic->wire.copy_byte_mask |= MLX5_CPY_REF_MASK; } else basic->wire.bs_selector = bs_selector(wire->sig.dif.pi_interval); basic->w_bfs_psv = cpu_to_be32(msig->psv_wire.psv_idx); mlx5_fill_inl_bsf(wire, &bsf->w_inl); break; default: return -EINVAL; } return 0; } static int set_sig_data_segment(const struct ib_sig_handover_wr *wr, struct mlx5_ib_qp *qp, void **seg, int *size) { struct ib_sig_attrs *sig_attrs = wr->sig_attrs; struct ib_mr *sig_mr = wr->sig_mr; struct mlx5_bsf *bsf; u32 data_len = wr->wr.sg_list->length; u32 data_key = wr->wr.sg_list->lkey; u64 data_va = wr->wr.sg_list->addr; int ret; int wqe_size; if (!wr->prot || (data_key == wr->prot->lkey && data_va == wr->prot->addr && data_len == wr->prot->length)) { /** * Source domain doesn't contain signature information * or data and protection are interleaved in memory. * So need construct: * ------------------ * | data_klm | * ------------------ * | BSF | * ------------------ **/ struct mlx5_klm *data_klm = *seg; data_klm->bcount = cpu_to_be32(data_len); data_klm->key = cpu_to_be32(data_key); data_klm->va = cpu_to_be64(data_va); wqe_size = ALIGN(sizeof(*data_klm), 64); } else { /** * Source domain contains signature information * So need construct a strided block format: * --------------------------- * | stride_block_ctrl | * --------------------------- * | data_klm | * --------------------------- * | prot_klm | * --------------------------- * | BSF | * --------------------------- **/ struct mlx5_stride_block_ctrl_seg *sblock_ctrl; struct mlx5_stride_block_entry *data_sentry; struct mlx5_stride_block_entry *prot_sentry; u32 prot_key = wr->prot->lkey; u64 prot_va = wr->prot->addr; u16 block_size = sig_attrs->mem.sig.dif.pi_interval; int prot_size; sblock_ctrl = *seg; data_sentry = (void *)sblock_ctrl + sizeof(*sblock_ctrl); prot_sentry = (void *)data_sentry + sizeof(*data_sentry); prot_size = prot_field_size(sig_attrs->mem.sig_type); if (!prot_size) { pr_err("Bad block size given: %u\n", block_size); return -EINVAL; } sblock_ctrl->bcount_per_cycle = cpu_to_be32(block_size + prot_size); sblock_ctrl->op = cpu_to_be32(MLX5_STRIDE_BLOCK_OP); sblock_ctrl->repeat_count = cpu_to_be32(data_len / block_size); sblock_ctrl->num_entries = cpu_to_be16(2); data_sentry->bcount = cpu_to_be16(block_size); data_sentry->key = cpu_to_be32(data_key); data_sentry->va = cpu_to_be64(data_va); data_sentry->stride = cpu_to_be16(block_size); prot_sentry->bcount = cpu_to_be16(prot_size); prot_sentry->key = cpu_to_be32(prot_key); prot_sentry->va = cpu_to_be64(prot_va); prot_sentry->stride = cpu_to_be16(prot_size); wqe_size = ALIGN(sizeof(*sblock_ctrl) + sizeof(*data_sentry) + sizeof(*prot_sentry), 64); } *seg += wqe_size; *size += wqe_size / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); bsf = *seg; ret = mlx5_set_bsf(sig_mr, sig_attrs, bsf, data_len); if (ret) return -EINVAL; *seg += sizeof(*bsf); *size += sizeof(*bsf) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); return 0; } static void set_sig_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_sig_handover_wr *wr, u32 size, u32 length, u32 pdn) { struct ib_mr *sig_mr = wr->sig_mr; u32 sig_key = sig_mr->rkey; u8 sigerr = to_mmr(sig_mr)->sig->sigerr_count & 1; memset(seg, 0, sizeof(*seg)); seg->flags = get_umr_flags(wr->access_flags) | MLX5_MKC_ACCESS_MODE_KLMS; seg->qpn_mkey7_0 = cpu_to_be32((sig_key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL | sigerr << 26 | MLX5_MKEY_BSF_EN | pdn); seg->len = cpu_to_be64(length); seg->xlt_oct_size = cpu_to_be32(get_xlt_octo(size)); seg->bsfs_octo_size = cpu_to_be32(MLX5_MKEY_BSF_OCTO_SIZE); } static void set_sig_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr, u32 size) { memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_FLAGS_INLINE | MLX5_FLAGS_CHECK_FREE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->bsf_octowords = cpu_to_be16(MLX5_MKEY_BSF_OCTO_SIZE); umr->mkey_mask = sig_mkey_mask(); } static int set_sig_umr_wr(const struct ib_send_wr *send_wr, struct mlx5_ib_qp *qp, void **seg, int *size) { const struct ib_sig_handover_wr *wr = sig_handover_wr(send_wr); struct mlx5_ib_mr *sig_mr = to_mmr(wr->sig_mr); u32 pdn = get_pd(qp)->pdn; u32 xlt_size; int region_len, ret; if (unlikely(wr->wr.num_sge != 1) || unlikely(wr->access_flags & IB_ACCESS_REMOTE_ATOMIC) || unlikely(!sig_mr->sig) || unlikely(!qp->signature_en) || unlikely(!sig_mr->sig->sig_status_checked)) return -EINVAL; /* length of the protected region, data + protection */ region_len = wr->wr.sg_list->length; if (wr->prot && (wr->prot->lkey != wr->wr.sg_list->lkey || wr->prot->addr != wr->wr.sg_list->addr || wr->prot->length != wr->wr.sg_list->length)) region_len += wr->prot->length; /** * KLM octoword size - if protection was provided * then we use strided block format (3 octowords), * else we use single KLM (1 octoword) **/ xlt_size = wr->prot ? 0x30 : sizeof(struct mlx5_klm); set_sig_umr_segment(*seg, xlt_size); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_sig_mkey_segment(*seg, wr, xlt_size, region_len, pdn); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); ret = set_sig_data_segment(wr, qp, seg, size); if (ret) return ret; sig_mr->sig->sig_status_checked = false; return 0; } static int set_psv_wr(struct ib_sig_domain *domain, u32 psv_idx, void **seg, int *size) { struct mlx5_seg_set_psv *psv_seg = *seg; memset(psv_seg, 0, sizeof(*psv_seg)); psv_seg->psv_num = cpu_to_be32(psv_idx); switch (domain->sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: psv_seg->transient_sig = cpu_to_be32(domain->sig.dif.bg << 16 | domain->sig.dif.app_tag); psv_seg->ref_tag = cpu_to_be32(domain->sig.dif.ref_tag); break; default: pr_err("Bad signature type (%d) is given.\n", domain->sig_type); return -EINVAL; } *seg += sizeof(*psv_seg); *size += sizeof(*psv_seg) / 16; return 0; } static int set_reg_wr(struct mlx5_ib_qp *qp, const struct ib_reg_wr *wr, void **seg, int *size) { struct mlx5_ib_mr *mr = to_mmr(wr->mr); struct mlx5_ib_pd *pd = to_mpd(qp->ibqp.pd); int mr_list_size = mr->ndescs * mr->desc_size; bool umr_inline = mr_list_size <= MLX5_IB_SQ_UMR_INLINE_THRESHOLD; if (unlikely(wr->wr.send_flags & IB_SEND_INLINE)) { mlx5_ib_warn(to_mdev(qp->ibqp.device), "Invalid IB_SEND_INLINE send flag\n"); return -EINVAL; } set_reg_umr_seg(*seg, mr, umr_inline); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_seg(*seg, mr, wr->key, wr->access); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); if (umr_inline) { set_reg_umr_inline_seg(*seg, qp, mr, mr_list_size); *size += get_xlt_octo(mr_list_size); } else { set_reg_data_seg(*seg, mr, pd); *seg += sizeof(struct mlx5_wqe_data_seg); *size += (sizeof(struct mlx5_wqe_data_seg) / 16); } return 0; } static void set_linv_wr(struct mlx5_ib_qp *qp, void **seg, int *size) { set_linv_umr_seg(*seg); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_linv_mkey_seg(*seg); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); } static void dump_wqe(struct mlx5_ib_qp *qp, int idx, int size_16) { __be32 *p = NULL; int tidx = idx; int i, j; pr_debug("dump wqe at %p\n", mlx5_get_send_wqe(qp, tidx)); for (i = 0, j = 0; i < size_16 * 4; i += 4, j += 4) { if ((i & 0xf) == 0) { void *buf = mlx5_get_send_wqe(qp, tidx); tidx = (tidx + 1) & (qp->sq.wqe_cnt - 1); p = buf; j = 0; } pr_debug("%08x %08x %08x %08x\n", be32_to_cpu(p[j]), be32_to_cpu(p[j + 1]), be32_to_cpu(p[j + 2]), be32_to_cpu(p[j + 3])); } } static int __begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq, bool send_signaled, bool solicited) { if (unlikely(mlx5_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq))) return -ENOMEM; *idx = qp->sq.cur_post & (qp->sq.wqe_cnt - 1); *seg = mlx5_get_send_wqe(qp, *idx); *ctrl = *seg; *(uint32_t *)(*seg + 8) = 0; (*ctrl)->imm = send_ieth(wr); (*ctrl)->fm_ce_se = qp->sq_signal_bits | (send_signaled ? MLX5_WQE_CTRL_CQ_UPDATE : 0) | (solicited ? MLX5_WQE_CTRL_SOLICITED : 0); *seg += sizeof(**ctrl); *size = sizeof(**ctrl) / 16; return 0; } static int begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq) { return __begin_wqe(qp, seg, ctrl, wr, idx, size, nreq, wr->send_flags & IB_SEND_SIGNALED, wr->send_flags & IB_SEND_SOLICITED); } static void finish_wqe(struct mlx5_ib_qp *qp, struct mlx5_wqe_ctrl_seg *ctrl, u8 size, unsigned idx, u64 wr_id, int nreq, u8 fence, u32 mlx5_opcode) { u8 opmod = 0; ctrl->opmod_idx_opcode = cpu_to_be32(((u32)(qp->sq.cur_post) << 8) | mlx5_opcode | ((u32)opmod << 24)); ctrl->qpn_ds = cpu_to_be32(size | (qp->trans_qp.base.mqp.qpn << 8)); ctrl->fm_ce_se |= fence; if (unlikely(qp->wq_sig)) ctrl->signature = wq_sig(ctrl); qp->sq.wrid[idx] = wr_id; qp->sq.w_list[idx].opcode = mlx5_opcode; qp->sq.wqe_head[idx] = qp->sq.head + nreq; qp->sq.cur_post += DIV_ROUND_UP(size * 16, MLX5_SEND_WQE_BB); qp->sq.w_list[idx].next = qp->sq.cur_post; } static int _mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr, bool drain) { struct mlx5_wqe_ctrl_seg *ctrl = NULL; /* compiler warning */ struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_qp *qp; struct mlx5_ib_mr *mr; struct mlx5_wqe_data_seg *dpseg; struct mlx5_wqe_xrc_seg *xrc; struct mlx5_bf *bf; int uninitialized_var(size); void *qend; unsigned long flags; unsigned idx; int err = 0; int num_sge; void *seg; int nreq; int i; u8 next_fence = 0; u8 fence; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_send(ibqp, wr, bad_wr); qp = to_mqp(ibqp); bf = &qp->bf; qend = qp->sq.qend; spin_lock_irqsave(&qp->sq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } for (nreq = 0; wr; nreq++, wr = wr->next) { if (unlikely(wr->opcode >= ARRAY_SIZE(mlx5_ib_opcode))) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } num_sge = wr->num_sge; if (unlikely(num_sge > qp->sq.max_gs)) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } err = begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } if (wr->opcode == IB_WR_LOCAL_INV || wr->opcode == IB_WR_REG_MR) { fence = dev->umr_fence; next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; } else if (wr->send_flags & IB_SEND_FENCE) { if (qp->next_fence) fence = MLX5_FENCE_MODE_SMALL_AND_FENCE; else fence = MLX5_FENCE_MODE_FENCE; } else { fence = qp->next_fence; } switch (ibqp->qp_type) { case IB_QPT_XRC_INI: xrc = seg; seg += sizeof(*xrc); size += sizeof(*xrc) / 16; /* fall through */ case IB_QPT_RC: switch (wr->opcode) { case IB_WR_RDMA_READ: case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; case IB_WR_ATOMIC_CMP_AND_SWP: case IB_WR_ATOMIC_FETCH_AND_ADD: case IB_WR_MASKED_ATOMIC_CMP_AND_SWP: mlx5_ib_warn(dev, "Atomic operations are not supported yet\n"); err = -ENOSYS; *bad_wr = wr; goto out; case IB_WR_LOCAL_INV: qp->sq.wr_data[idx] = IB_WR_LOCAL_INV; ctrl->imm = cpu_to_be32(wr->ex.invalidate_rkey); set_linv_wr(qp, &seg, &size); num_sge = 0; break; case IB_WR_REG_MR: qp->sq.wr_data[idx] = IB_WR_REG_MR; ctrl->imm = cpu_to_be32(reg_wr(wr)->key); err = set_reg_wr(qp, reg_wr(wr), &seg, &size); if (err) { *bad_wr = wr; goto out; } num_sge = 0; break; case IB_WR_REG_SIG_MR: qp->sq.wr_data[idx] = IB_WR_REG_SIG_MR; mr = to_mmr(sig_handover_wr(wr)->sig_mr); ctrl->imm = cpu_to_be32(mr->ibmr.rkey); err = set_sig_umr_wr(wr, qp, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_UMR); /* * SET_PSV WQEs are not signaled and solicited * on error */ err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->mem, mr->sig->psv_memory.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->wire, mr->sig->psv_wire.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); qp->next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; num_sge = 0; goto skip_psv; default: break; } break; case IB_QPT_UC: switch (wr->opcode) { case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; default: break; } break; case IB_QPT_SMI: if (unlikely(!mdev->port_caps[qp->port - 1].has_smi)) { mlx5_ib_warn(dev, "Send SMP MADs is not allowed\n"); err = -EPERM; *bad_wr = wr; goto out; } /* fall through */ case MLX5_IB_QPT_HW_GSI: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; case IB_QPT_UD: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); /* handle qp that supports ud offload */ if (qp->flags & IB_QP_CREATE_IPOIB_UD_LSO) { struct mlx5_wqe_eth_pad *pad; pad = seg; memset(pad, 0, sizeof(struct mlx5_wqe_eth_pad)); seg += sizeof(struct mlx5_wqe_eth_pad); size += sizeof(struct mlx5_wqe_eth_pad) / 16; seg = set_eth_seg(seg, wr, qend, qp, &size); if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); } break; case MLX5_IB_QPT_REG_UMR: if (wr->opcode != MLX5_IB_WR_UMR) { err = -EINVAL; mlx5_ib_warn(dev, "bad opcode\n"); goto out; } qp->sq.wr_data[idx] = MLX5_IB_WR_UMR; ctrl->imm = cpu_to_be32(umr_wr(wr)->mkey); err = set_reg_umr_segment(dev, seg, wr, !!(MLX5_CAP_GEN(mdev, atomic))); if (unlikely(err)) goto out; seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_segment(seg, wr); seg += sizeof(struct mlx5_mkey_seg); size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; default: break; } if (wr->send_flags & IB_SEND_INLINE && num_sge) { int uninitialized_var(sz); err = set_data_inl_seg(qp, wr, seg, &sz); if (unlikely(err)) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } size += sz; } else { dpseg = seg; for (i = 0; i < num_sge; i++) { if (unlikely(dpseg == qend)) { seg = mlx5_get_send_wqe(qp, 0); dpseg = seg; } if (likely(wr->sg_list[i].length)) { set_data_ptr_seg(dpseg, wr->sg_list + i); size += sizeof(struct mlx5_wqe_data_seg) / 16; dpseg++; } } } qp->next_fence = next_fence; finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, mlx5_ib_opcode[wr->opcode]); skip_psv: if (0) dump_wqe(qp, idx, size); } out: if (likely(nreq)) { qp->sq.head += nreq; /* Make sure that descriptors are written before * updating doorbell record and ringing the doorbell */ wmb(); qp->db.db[MLX5_SND_DBR] = cpu_to_be32(qp->sq.cur_post); /* Make sure doorbell record is visible to the HCA before * we hit doorbell */ wmb(); /* currently we support only regular doorbells */ mlx5_write64((__be32 *)ctrl, bf->bfreg->map + bf->offset, NULL); /* Make sure doorbells don't leak out of SQ spinlock * and reach the HCA out of order. */ mmiowb(); bf->offset ^= bf->buf_size; } spin_unlock_irqrestore(&qp->sq.lock, flags); return err; } int mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr) { return _mlx5_ib_post_send(ibqp, wr, bad_wr, false); } static void set_sig_seg(struct mlx5_rwqe_sig *sig, int size) { sig->signature = calc_sig(sig, size); } static int _mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr, bool drain) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_wqe_data_seg *scat; struct mlx5_rwqe_sig *sig; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; unsigned long flags; int err = 0; int nreq; int ind; int i; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_recv(ibqp, wr, bad_wr); spin_lock_irqsave(&qp->rq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } ind = qp->rq.head & (qp->rq.wqe_cnt - 1); for (nreq = 0; wr; nreq++, wr = wr->next) { if (mlx5_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) { err = -ENOMEM; *bad_wr = wr; goto out; } if (unlikely(wr->num_sge > qp->rq.max_gs)) { err = -EINVAL; *bad_wr = wr; goto out; } scat = get_recv_wqe(qp, ind); if (qp->wq_sig) scat++; for (i = 0; i < wr->num_sge; i++) set_data_ptr_seg(scat + i, wr->sg_list + i); if (i < qp->rq.max_gs) { scat[i].byte_count = 0; scat[i].lkey = cpu_to_be32(MLX5_INVALID_LKEY); scat[i].addr = 0; } if (qp->wq_sig) { sig = (struct mlx5_rwqe_sig *)scat; set_sig_seg(sig, (qp->rq.max_gs + 1) << 2); } qp->rq.wrid[ind] = wr->wr_id; ind = (ind + 1) & (qp->rq.wqe_cnt - 1); } out: if (likely(nreq)) { qp->rq.head += nreq; /* Make sure that descriptors are written before * doorbell record. */ wmb(); *qp->db.db = cpu_to_be32(qp->rq.head & 0xffff); } spin_unlock_irqrestore(&qp->rq.lock, flags); return err; } int mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr) { return _mlx5_ib_post_recv(ibqp, wr, bad_wr, false); } static inline enum ib_qp_state to_ib_qp_state(enum mlx5_qp_state mlx5_state) { switch (mlx5_state) { case MLX5_QP_STATE_RST: return IB_QPS_RESET; case MLX5_QP_STATE_INIT: return IB_QPS_INIT; case MLX5_QP_STATE_RTR: return IB_QPS_RTR; case MLX5_QP_STATE_RTS: return IB_QPS_RTS; case MLX5_QP_STATE_SQ_DRAINING: case MLX5_QP_STATE_SQD: return IB_QPS_SQD; case MLX5_QP_STATE_SQER: return IB_QPS_SQE; case MLX5_QP_STATE_ERR: return IB_QPS_ERR; default: return -1; } } static inline enum ib_mig_state to_ib_mig_state(int mlx5_mig_state) { switch (mlx5_mig_state) { case MLX5_QP_PM_ARMED: return IB_MIG_ARMED; case MLX5_QP_PM_REARM: return IB_MIG_REARM; case MLX5_QP_PM_MIGRATED: return IB_MIG_MIGRATED; default: return -1; } } static int to_ib_qp_access_flags(int mlx5_flags) { int ib_flags = 0; if (mlx5_flags & MLX5_QP_BIT_RRE) ib_flags |= IB_ACCESS_REMOTE_READ; if (mlx5_flags & MLX5_QP_BIT_RWE) ib_flags |= IB_ACCESS_REMOTE_WRITE; if (mlx5_flags & MLX5_QP_BIT_RAE) ib_flags |= IB_ACCESS_REMOTE_ATOMIC; return ib_flags; } static void to_rdma_ah_attr(struct mlx5_ib_dev *ibdev, struct rdma_ah_attr *ah_attr, struct mlx5_qp_path *path) { memset(ah_attr, 0, sizeof(*ah_attr)); if (!path->port || path->port > ibdev->num_ports) return; ah_attr->type = rdma_ah_find_type(&ibdev->ib_dev, path->port); rdma_ah_set_port_num(ah_attr, path->port); rdma_ah_set_sl(ah_attr, path->dci_cfi_prio_sl & 0xf); rdma_ah_set_dlid(ah_attr, be16_to_cpu(path->rlid)); rdma_ah_set_path_bits(ah_attr, path->grh_mlid & 0x7f); rdma_ah_set_static_rate(ah_attr, path->static_rate ? path->static_rate - 5 : 0); if (path->grh_mlid & (1 << 7)) { u32 tc_fl = be32_to_cpu(path->tclass_flowlabel); rdma_ah_set_grh(ah_attr, NULL, tc_fl & 0xfffff, path->mgid_index, path->hop_limit, (tc_fl >> 20) & 0xff); rdma_ah_set_dgid_raw(ah_attr, path->rgid); } } static int query_raw_packet_qp_sq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, u8 *sq_state) { int err; err = mlx5_core_query_sq_state(dev->mdev, sq->base.mqp.qpn, sq_state); if (err) goto out; sq->state = *sq_state; out: return err; } static int query_raw_packet_qp_rq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u8 *rq_state) { void *out; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(query_rq_out); out = kvzalloc(inlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_query_rq(dev->mdev, rq->base.mqp.qpn, out); if (err) goto out; rqc = MLX5_ADDR_OF(query_rq_out, out, rq_context); *rq_state = MLX5_GET(rqc, rqc, state); rq->state = *rq_state; out: kvfree(out); return err; } static int sqrq_state_to_qp_state(u8 sq_state, u8 rq_state, struct mlx5_ib_qp *qp, u8 *qp_state) { static const u8 sqrq_trans[MLX5_RQ_NUM_STATE][MLX5_SQ_NUM_STATE] = { [MLX5_RQC_STATE_RST] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE_BAD, [MLX5_SQ_STATE_NA] = IB_QPS_RESET, }, [MLX5_RQC_STATE_RDY] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = IB_QPS_SQE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE, }, [MLX5_RQC_STATE_ERR] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = IB_QPS_ERR, [MLX5_SQ_STATE_NA] = IB_QPS_ERR, }, [MLX5_RQ_STATE_NA] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE_BAD, }, }; *qp_state = sqrq_trans[rq_state][sq_state]; if (*qp_state == MLX5_QP_STATE_BAD) { WARN(1, "Buggy Raw Packet QP state, SQ 0x%x state: 0x%x, RQ 0x%x state: 0x%x", qp->raw_packet_qp.sq.base.mqp.qpn, sq_state, qp->raw_packet_qp.rq.base.mqp.qpn, rq_state); return -EINVAL; } if (*qp_state == MLX5_QP_STATE) *qp_state = qp->state; return 0; } static int query_raw_packet_qp_state(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u8 *raw_packet_qp_state) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; int err; u8 sq_state = MLX5_SQ_STATE_NA; u8 rq_state = MLX5_RQ_STATE_NA; if (qp->sq.wqe_cnt) { err = query_raw_packet_qp_sq_state(dev, sq, &sq_state); if (err) return err; } if (qp->rq.wqe_cnt) { err = query_raw_packet_qp_rq_state(dev, rq, &rq_state); if (err) return err; } return sqrq_state_to_qp_state(sq_state, rq_state, qp, raw_packet_qp_state); } static int query_qp_attr(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_qp_attr *qp_attr) { int outlen = MLX5_ST_SZ_BYTES(query_qp_out); struct mlx5_qp_context *context; int mlx5_state; u32 *outb; int err = 0; outb = kzalloc(outlen, GFP_KERNEL); if (!outb) return -ENOMEM; err = mlx5_core_qp_query(dev->mdev, &qp->trans_qp.base.mqp, outb, outlen); if (err) goto out; /* FIXME: use MLX5_GET rather than mlx5_qp_context manual struct */ context = (struct mlx5_qp_context *)MLX5_ADDR_OF(query_qp_out, outb, qpc); mlx5_state = be32_to_cpu(context->flags) >> 28; qp->state = to_ib_qp_state(mlx5_state); qp_attr->path_mtu = context->mtu_msgmax >> 5; qp_attr->path_mig_state = to_ib_mig_state((be32_to_cpu(context->flags) >> 11) & 0x3); qp_attr->qkey = be32_to_cpu(context->qkey); qp_attr->rq_psn = be32_to_cpu(context->rnr_nextrecvpsn) & 0xffffff; qp_attr->sq_psn = be32_to_cpu(context->next_send_psn) & 0xffffff; qp_attr->dest_qp_num = be32_to_cpu(context->log_pg_sz_remote_qpn) & 0xffffff; qp_attr->qp_access_flags = to_ib_qp_access_flags(be32_to_cpu(context->params2)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC) { to_rdma_ah_attr(dev, &qp_attr->ah_attr, &context->pri_path); to_rdma_ah_attr(dev, &qp_attr->alt_ah_attr, &context->alt_path); qp_attr->alt_pkey_index = be16_to_cpu(context->alt_path.pkey_index); qp_attr->alt_port_num = rdma_ah_get_port_num(&qp_attr->alt_ah_attr); } qp_attr->pkey_index = be16_to_cpu(context->pri_path.pkey_index); qp_attr->port_num = context->pri_path.port; /* qp_attr->en_sqd_async_notify is only applicable in modify qp */ qp_attr->sq_draining = mlx5_state == MLX5_QP_STATE_SQ_DRAINING; qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context->params1) >> 21) & 0x7); qp_attr->max_dest_rd_atomic = 1 << ((be32_to_cpu(context->params2) >> 21) & 0x7); qp_attr->min_rnr_timer = (be32_to_cpu(context->rnr_nextrecvpsn) >> 24) & 0x1f; qp_attr->timeout = context->pri_path.ackto_lt >> 3; qp_attr->retry_cnt = (be32_to_cpu(context->params1) >> 16) & 0x7; qp_attr->rnr_retry = (be32_to_cpu(context->params1) >> 13) & 0x7; qp_attr->alt_timeout = context->alt_path.ackto_lt >> 3; out: kfree(outb); return err; } static int mlx5_ib_dct_query_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *mqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_core_dct *dct = &mqp->dct.mdct; u32 *out; u32 access_flags = 0; int outlen = MLX5_ST_SZ_BYTES(query_dct_out); void *dctc; int err; int supported_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT | IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU | IB_QP_PKEY_INDEX; if (qp_attr_mask & ~supported_mask) return -EINVAL; if (mqp->state != IB_QPS_RTR) return -EINVAL; out = kzalloc(outlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_dct_query(dev->mdev, dct, out, outlen); if (err) goto out; dctc = MLX5_ADDR_OF(query_dct_out, out, dct_context_entry); if (qp_attr_mask & IB_QP_STATE) qp_attr->qp_state = IB_QPS_RTR; if (qp_attr_mask & IB_QP_ACCESS_FLAGS) { if (MLX5_GET(dctc, dctc, rre)) access_flags |= IB_ACCESS_REMOTE_READ; if (MLX5_GET(dctc, dctc, rwe)) access_flags |= IB_ACCESS_REMOTE_WRITE; if (MLX5_GET(dctc, dctc, rae)) access_flags |= IB_ACCESS_REMOTE_ATOMIC; qp_attr->qp_access_flags = access_flags; } if (qp_attr_mask & IB_QP_PORT) qp_attr->port_num = MLX5_GET(dctc, dctc, port); if (qp_attr_mask & IB_QP_MIN_RNR_TIMER) qp_attr->min_rnr_timer = MLX5_GET(dctc, dctc, min_rnr_nak); if (qp_attr_mask & IB_QP_AV) { qp_attr->ah_attr.grh.traffic_class = MLX5_GET(dctc, dctc, tclass); qp_attr->ah_attr.grh.flow_label = MLX5_GET(dctc, dctc, flow_label); qp_attr->ah_attr.grh.sgid_index = MLX5_GET(dctc, dctc, my_addr_index); qp_attr->ah_attr.grh.hop_limit = MLX5_GET(dctc, dctc, hop_limit); } if (qp_attr_mask & IB_QP_PATH_MTU) qp_attr->path_mtu = MLX5_GET(dctc, dctc, mtu); if (qp_attr_mask & IB_QP_PKEY_INDEX) qp_attr->pkey_index = MLX5_GET(dctc, dctc, pkey_index); out: kfree(out); return err; } int mlx5_ib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); int err = 0; u8 raw_packet_qp_state; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_query_qp(ibqp, qp_attr, qp_attr_mask, qp_init_attr); /* Not all of output fields are applicable, make sure to zero them */ memset(qp_init_attr, 0, sizeof(*qp_init_attr)); memset(qp_attr, 0, sizeof(*qp_attr)); if (unlikely(qp->qp_sub_type == MLX5_IB_QPT_DCT)) return mlx5_ib_dct_query_qp(dev, qp, qp_attr, qp_attr_mask, qp_init_attr); mutex_lock(&qp->mutex); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { err = query_raw_packet_qp_state(dev, qp, &raw_packet_qp_state); if (err) goto out; qp->state = raw_packet_qp_state; qp_attr->port_num = 1; } else { err = query_qp_attr(dev, qp, qp_attr); if (err) goto out; } qp_attr->qp_state = qp->state; qp_attr->cur_qp_state = qp_attr->qp_state; qp_attr->cap.max_recv_wr = qp->rq.wqe_cnt; qp_attr->cap.max_recv_sge = qp->rq.max_gs; if (!ibqp->uobject) { qp_attr->cap.max_send_wr = qp->sq.max_post; qp_attr->cap.max_send_sge = qp->sq.max_gs; qp_init_attr->qp_context = ibqp->qp_context; } else { qp_attr->cap.max_send_wr = 0; qp_attr->cap.max_send_sge = 0; } qp_init_attr->qp_type = ibqp->qp_type; qp_init_attr->recv_cq = ibqp->recv_cq; qp_init_attr->send_cq = ibqp->send_cq; qp_init_attr->srq = ibqp->srq; qp_attr->cap.max_inline_data = qp->max_inline_data; qp_init_attr->cap = qp_attr->cap; qp_init_attr->create_flags = 0; if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) qp_init_attr->create_flags |= IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK; if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) qp_init_attr->create_flags |= IB_QP_CREATE_CROSS_CHANNEL; if (qp->flags & MLX5_IB_QP_MANAGED_SEND) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_SEND; if (qp->flags & MLX5_IB_QP_MANAGED_RECV) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_RECV; if (qp->flags & MLX5_IB_QP_SQPN_QP1) qp_init_attr->create_flags |= mlx5_ib_create_qp_sqpn_qp1(); qp_init_attr->sq_sig_type = qp->sq_signal_bits & MLX5_WQE_CTRL_CQ_UPDATE ? IB_SIGNAL_ALL_WR : IB_SIGNAL_REQ_WR; out: mutex_unlock(&qp->mutex); return err; } struct ib_xrcd *mlx5_ib_alloc_xrcd(struct ib_device *ibdev, struct ib_ucontext *context, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_xrcd *xrcd; int err; if (!MLX5_CAP_GEN(dev->mdev, xrc)) return ERR_PTR(-ENOSYS); xrcd = kmalloc(sizeof(*xrcd), GFP_KERNEL); if (!xrcd) return ERR_PTR(-ENOMEM); err = mlx5_core_xrcd_alloc(dev->mdev, &xrcd->xrcdn); if (err) { kfree(xrcd); return ERR_PTR(-ENOMEM); } return &xrcd->ibxrcd; } int mlx5_ib_dealloc_xrcd(struct ib_xrcd *xrcd) { struct mlx5_ib_dev *dev = to_mdev(xrcd->device); u32 xrcdn = to_mxrcd(xrcd)->xrcdn; int err; err = mlx5_core_xrcd_dealloc(dev->mdev, xrcdn); if (err) mlx5_ib_warn(dev, "failed to dealloc xrcdn 0x%x\n", xrcdn); kfree(xrcd); return 0; } static void mlx5_ib_wq_event(struct mlx5_core_qp *core_qp, int type) { struct mlx5_ib_rwq *rwq = to_mibrwq(core_qp); struct mlx5_ib_dev *dev = to_mdev(rwq->ibwq.device); struct ib_event event; if (rwq->ibwq.event_handler) { event.device = rwq->ibwq.device; event.element.wq = &rwq->ibwq; switch (type) { case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_WQ_FATAL; break; default: mlx5_ib_warn(dev, "Unexpected event type %d on WQ %06x\n", type, core_qp->qpn); return; } rwq->ibwq.event_handler(&event, rwq->ibwq.wq_context); } } static int set_delay_drop(struct mlx5_ib_dev *dev) { int err = 0; mutex_lock(&dev->delay_drop.lock); if (dev->delay_drop.activate) goto out; err = mlx5_core_set_delay_drop(dev->mdev, dev->delay_drop.timeout); if (err) goto out; dev->delay_drop.activate = true; out: mutex_unlock(&dev->delay_drop.lock); if (!err) atomic_inc(&dev->delay_drop.rqs_cnt); return err; } static int create_rq(struct mlx5_ib_rwq *rwq, struct ib_pd *pd, struct ib_wq_init_attr *init_attr) { struct mlx5_ib_dev *dev; int has_net_offloads; __be64 *rq_pas0; void *in; void *rqc; void *wq; int inlen; int err; dev = to_mdev(pd->device); inlen = MLX5_ST_SZ_BYTES(create_rq_in) + sizeof(u64) * rwq->rq_num_pas; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, user_index, rwq->user_index); MLX5_SET(rqc, rqc, cqn, to_mcq(init_attr->cq)->mcq.cqn); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ ? MLX5_WQ_TYPE_CYCLIC_STRIDING_RQ : MLX5_WQ_TYPE_CYCLIC); if (init_attr->create_flags & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "Scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } else { MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } } MLX5_SET(wq, wq, log_wq_stride, rwq->log_rq_stride); if (rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ) { MLX5_SET(wq, wq, two_byte_shift_en, rwq->two_byte_shift_en); MLX5_SET(wq, wq, log_wqe_stride_size, rwq->single_stride_log_num_of_bytes - MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES); MLX5_SET(wq, wq, log_wqe_num_of_strides, rwq->log_num_strides - MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES); } MLX5_SET(wq, wq, log_wq_sz, rwq->log_rq_size); MLX5_SET(wq, wq, pd, to_mpd(pd)->pdn); MLX5_SET(wq, wq, page_offset, rwq->rq_page_offset); MLX5_SET(wq, wq, log_wq_pg_sz, rwq->log_page_size); MLX5_SET(wq, wq, wq_signature, rwq->wq_sig); MLX5_SET64(wq, wq, dbr_addr, rwq->db.dma); has_net_offloads = MLX5_CAP_GEN(dev->mdev, eth_net_offloads); if (init_attr->create_flags & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not supported\n"); err = -EOPNOTSUPP; goto out; } } else { MLX5_SET(rqc, rqc, vsd, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_SCATTER_FCS) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, scatter_fcs))) { mlx5_ib_dbg(dev, "Scatter FCS is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, scatter_fcs, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { if (!(dev->ib_dev.attrs.raw_packet_caps & IB_RAW_PACKET_CAP_DELAY_DROP)) { mlx5_ib_dbg(dev, "Delay drop is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, delay_drop_en, 1); } rq_pas0 = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, rwq->umem, rwq->page_shift, rq_pas0, 0); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rwq->core_qp); if (!err && init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { err = set_delay_drop(dev); if (err) { mlx5_ib_warn(dev, "Failed to enable delay drop err=%d\n", err); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); } else { rwq->create_flags |= MLX5_IB_WQ_FLAGS_DELAY_DROP; } } out: kvfree(in); return err; } static int set_user_rq_size(struct mlx5_ib_dev *dev, struct ib_wq_init_attr *wq_init_attr, struct mlx5_ib_create_wq *ucmd, struct mlx5_ib_rwq *rwq) { /* Sanity check RQ size before proceeding */ if (wq_init_attr->max_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_wq_sz))) return -EINVAL; if (!ucmd->rq_wqe_count) return -EINVAL; rwq->wqe_count = ucmd->rq_wqe_count; rwq->wqe_shift = ucmd->rq_wqe_shift; if (check_shl_overflow(rwq->wqe_count, rwq->wqe_shift, &rwq->buf_size)) return -EINVAL; rwq->log_rq_stride = rwq->wqe_shift; rwq->log_rq_size = ilog2(rwq->wqe_count); return 0; } static int prepare_user_rq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_dev *dev = to_mdev(pd->device); struct mlx5_ib_create_wq ucmd = {}; int err; size_t required_cmd_sz; required_cmd_sz = offsetof(typeof(ucmd), single_stride_log_num_of_bytes) + sizeof(ucmd.single_stride_log_num_of_bytes); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask & (~MLX5_IB_CREATE_WQ_STRIDING_RQ)) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } else if (ucmd.comp_mask & MLX5_IB_CREATE_WQ_STRIDING_RQ) { if (!MLX5_CAP_GEN(dev->mdev, striding_rq)) { mlx5_ib_dbg(dev, "Striding RQ is not supported\n"); return -EOPNOTSUPP; } if ((ucmd.single_stride_log_num_of_bytes < MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES) || (ucmd.single_stride_log_num_of_bytes > MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES)) { mlx5_ib_dbg(dev, "Invalid log stride size (%u. Range is %u - %u)\n", ucmd.single_stride_log_num_of_bytes, MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES, MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES); return -EINVAL; } if ((ucmd.single_wqe_log_num_of_strides > MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES) || (ucmd.single_wqe_log_num_of_strides < MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES)) { mlx5_ib_dbg(dev, "Invalid log num strides (%u. Range is %u - %u)\n", ucmd.single_wqe_log_num_of_strides, MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES, MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES); return -EINVAL; } rwq->single_stride_log_num_of_bytes = ucmd.single_stride_log_num_of_bytes; rwq->log_num_strides = ucmd.single_wqe_log_num_of_strides; rwq->two_byte_shift_en = !!ucmd.two_byte_shift_en; rwq->create_flags |= MLX5_IB_WQ_FLAGS_STRIDING_RQ; } err = set_user_rq_size(dev, init_attr, &ucmd, rwq); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } err = create_user_rq(dev, pd, rwq, &ucmd); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); if (err) return err; } rwq->user_index = ucmd.user_index; return 0; } struct ib_wq *mlx5_ib_create_wq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_rwq *rwq; struct mlx5_ib_create_wq_resp resp = {}; size_t min_resp_len; int err; if (!udata) return ERR_PTR(-ENOSYS); min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); dev = to_mdev(pd->device); switch (init_attr->wq_type) { case IB_WQT_RQ: rwq = kzalloc(sizeof(*rwq), GFP_KERNEL); if (!rwq) return ERR_PTR(-ENOMEM); err = prepare_user_rq(pd, init_attr, udata, rwq); if (err) goto err; err = create_rq(rwq, pd, init_attr); if (err) goto err_user_rq; break; default: mlx5_ib_dbg(dev, "unsupported wq type %d\n", init_attr->wq_type); return ERR_PTR(-EINVAL); } rwq->ibwq.wq_num = rwq->core_qp.qpn; rwq->ibwq.state = IB_WQS_RESET; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } rwq->core_qp.event = mlx5_ib_wq_event; rwq->ibwq.event_handler = init_attr->event_handler; return &rwq->ibwq; err_copy: mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); err_user_rq: destroy_user_rq(dev, pd, rwq); err: kfree(rwq); return ERR_PTR(err); } int mlx5_ib_destroy_wq(struct ib_wq *wq) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); destroy_user_rq(dev, wq->pd, rwq); kfree(rwq); return 0; } struct ib_rwq_ind_table *mlx5_ib_create_rwq_ind_table(struct ib_device *device, struct ib_rwq_ind_table_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(device); struct mlx5_ib_rwq_ind_table *rwq_ind_tbl; int sz = 1 << init_attr->log_ind_tbl_size; struct mlx5_ib_create_rwq_ind_tbl_resp resp = {}; size_t min_resp_len; int inlen; int err; int i; u32 *in; void *rqtc; if (udata->inlen > 0 && !ib_is_udata_cleared(udata, 0, udata->inlen)) return ERR_PTR(-EOPNOTSUPP); if (init_attr->log_ind_tbl_size > MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)) { mlx5_ib_dbg(dev, "log_ind_tbl_size = %d is bigger than supported = %d\n", init_attr->log_ind_tbl_size, MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)); return ERR_PTR(-EINVAL); } min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); rwq_ind_tbl = kzalloc(sizeof(*rwq_ind_tbl), GFP_KERNEL); if (!rwq_ind_tbl) return ERR_PTR(-ENOMEM); inlen = MLX5_ST_SZ_BYTES(create_rqt_in) + sizeof(u32) * sz; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err; } rqtc = MLX5_ADDR_OF(create_rqt_in, in, rqt_context); MLX5_SET(rqtc, rqtc, rqt_actual_size, sz); MLX5_SET(rqtc, rqtc, rqt_max_size, sz); for (i = 0; i < sz; i++) MLX5_SET(rqtc, rqtc, rq_num[i], init_attr->ind_tbl[i]->wq_num); err = mlx5_core_create_rqt(dev->mdev, in, inlen, &rwq_ind_tbl->rqtn); kvfree(in); if (err) goto err; rwq_ind_tbl->ib_rwq_ind_tbl.ind_tbl_num = rwq_ind_tbl->rqtn; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } return &rwq_ind_tbl->ib_rwq_ind_tbl; err_copy: mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); err: kfree(rwq_ind_tbl); return ERR_PTR(err); } int mlx5_ib_destroy_rwq_ind_table(struct ib_rwq_ind_table *ib_rwq_ind_tbl) { struct mlx5_ib_rwq_ind_table *rwq_ind_tbl = to_mrwq_ind_table(ib_rwq_ind_tbl); struct mlx5_ib_dev *dev = to_mdev(ib_rwq_ind_tbl->device); mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); kfree(rwq_ind_tbl); return 0; } int mlx5_ib_modify_wq(struct ib_wq *wq, struct ib_wq_attr *wq_attr, u32 wq_attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); struct mlx5_ib_modify_wq ucmd = {}; size_t required_cmd_sz; int curr_wq_state; int wq_state; int inlen; int err; void *rqc; void *in; required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) return -EFAULT; if (ucmd.comp_mask || ucmd.reserved) return -EOPNOTSUPP; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); curr_wq_state = (wq_attr_mask & IB_WQ_CUR_STATE) ? wq_attr->curr_wq_state : wq->state; wq_state = (wq_attr_mask & IB_WQ_STATE) ? wq_attr->wq_state : curr_wq_state; if (curr_wq_state == IB_WQS_ERR) curr_wq_state = MLX5_RQC_STATE_ERR; if (wq_state == IB_WQS_ERR) wq_state = MLX5_RQC_STATE_ERR; MLX5_SET(modify_rq_in, in, rq_state, curr_wq_state); MLX5_SET(rqc, rqc, state, wq_state); if (wq_attr_mask & IB_WQ_FLAGS) { if (wq_attr->flags_mask & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not " "supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_VSD); MLX5_SET(rqc, rqc, vsd, (wq_attr->flags & IB_WQ_FLAGS_CVLAN_STRIPPING) ? 0 : 1); } if (wq_attr->flags_mask & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { mlx5_ib_dbg(dev, "Modifying scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } } if (curr_wq_state == IB_WQS_RESET && wq_state == IB_WQS_RDY) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, dev->port->cnts.set_id); } else pr_info_once("%s: Receive WQ counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rwq->core_qp.qpn, in, inlen); if (!err) rwq->ibwq.state = (wq_state == MLX5_RQC_STATE_ERR) ? IB_WQS_ERR : wq_state; out: kvfree(in); return err; } struct mlx5_ib_drain_cqe { struct ib_cqe cqe; struct completion done; }; static void mlx5_ib_drain_qp_done(struct ib_cq *cq, struct ib_wc *wc) { struct mlx5_ib_drain_cqe *cqe = container_of(wc->wr_cqe, struct mlx5_ib_drain_cqe, cqe); complete(&cqe->done); } /* This function returns only once the drained WR was completed */ static void handle_drain_completion(struct ib_cq *cq, struct mlx5_ib_drain_cqe *sdrain, struct mlx5_ib_dev *dev) { struct mlx5_core_dev *mdev = dev->mdev; if (cq->poll_ctx == IB_POLL_DIRECT) { while (wait_for_completion_timeout(&sdrain->done, HZ / 10) <= 0) ib_process_cq_direct(cq, -1); return; } if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) { struct mlx5_ib_cq *mcq = to_mcq(cq); bool triggered = false; unsigned long flags; spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); /* Make sure that the CQ handler won't run if wasn't run yet */ if (!mcq->mcq.reset_notify_added) mcq->mcq.reset_notify_added = 1; else triggered = true; spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (triggered) { /* Wait for any scheduled/running task to be ended */ switch (cq->poll_ctx) { case IB_POLL_SOFTIRQ: irq_poll_disable(&cq->iop); irq_poll_enable(&cq->iop); break; case IB_POLL_WORKQUEUE: cancel_work_sync(&cq->work); break; default: WARN_ON_ONCE(1); } } /* Run the CQ handler - this makes sure that the drain WR will * be processed if wasn't processed yet. */ mcq->mcq.comp(&mcq->mcq); } wait_for_completion(&sdrain->done); } void mlx5_ib_drain_sq(struct ib_qp *qp) { struct ib_cq *cq = qp->send_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe sdrain; const struct ib_send_wr *bad_swr; struct ib_rdma_wr swr = { .wr = { .next = NULL, { .wr_cqe = &sdrain.cqe, }, .opcode = IB_WR_RDMA_WRITE, }, }; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } sdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&sdrain.done); ret = _mlx5_ib_post_send(qp, &swr.wr, &bad_swr, true); if (ret) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } handle_drain_completion(cq, &sdrain, dev); } void mlx5_ib_drain_rq(struct ib_qp *qp) { struct ib_cq *cq = qp->recv_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe rdrain; struct ib_recv_wr rwr = {}; const struct ib_recv_wr *bad_rwr; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } rwr.wr_cqe = &rdrain.cqe; rdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&rdrain.done); ret = _mlx5_ib_post_recv(qp, &rwr, &bad_rwr, true); if (ret) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } handle_drain_completion(cq, &rdrain, dev); }
/* * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/module.h> #include <rdma/ib_umem.h> #include <rdma/ib_cache.h> #include <rdma/ib_user_verbs.h> #include <linux/mlx5/fs.h> #include "mlx5_ib.h" #include "ib_rep.h" /* not supported currently */ static int wq_signature; enum { MLX5_IB_ACK_REQ_FREQ = 8, }; enum { MLX5_IB_DEFAULT_SCHED_QUEUE = 0x83, MLX5_IB_DEFAULT_QP0_SCHED_QUEUE = 0x3f, MLX5_IB_LINK_TYPE_IB = 0, MLX5_IB_LINK_TYPE_ETH = 1 }; enum { MLX5_IB_SQ_STRIDE = 6, MLX5_IB_SQ_UMR_INLINE_THRESHOLD = 64, }; static const u32 mlx5_ib_opcode[] = { [IB_WR_SEND] = MLX5_OPCODE_SEND, [IB_WR_LSO] = MLX5_OPCODE_LSO, [IB_WR_SEND_WITH_IMM] = MLX5_OPCODE_SEND_IMM, [IB_WR_RDMA_WRITE] = MLX5_OPCODE_RDMA_WRITE, [IB_WR_RDMA_WRITE_WITH_IMM] = MLX5_OPCODE_RDMA_WRITE_IMM, [IB_WR_RDMA_READ] = MLX5_OPCODE_RDMA_READ, [IB_WR_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_CS, [IB_WR_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_FA, [IB_WR_SEND_WITH_INV] = MLX5_OPCODE_SEND_INVAL, [IB_WR_LOCAL_INV] = MLX5_OPCODE_UMR, [IB_WR_REG_MR] = MLX5_OPCODE_UMR, [IB_WR_MASKED_ATOMIC_CMP_AND_SWP] = MLX5_OPCODE_ATOMIC_MASKED_CS, [IB_WR_MASKED_ATOMIC_FETCH_AND_ADD] = MLX5_OPCODE_ATOMIC_MASKED_FA, [MLX5_IB_WR_UMR] = MLX5_OPCODE_UMR, }; struct mlx5_wqe_eth_pad { u8 rsvd0[16]; }; enum raw_qp_set_mask_map { MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID = 1UL << 0, MLX5_RAW_QP_RATE_LIMIT = 1UL << 1, }; struct mlx5_modify_raw_qp_param { u16 operation; u32 set_mask; /* raw_qp_set_mask_map */ struct mlx5_rate_limit rl; u8 rq_q_ctr_id; }; static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq); static int is_qp0(enum ib_qp_type qp_type) { return qp_type == IB_QPT_SMI; } static int is_sqp(enum ib_qp_type qp_type) { return is_qp0(qp_type) || is_qp1(qp_type); } static void *get_wqe(struct mlx5_ib_qp *qp, int offset) { return mlx5_buf_offset(&qp->buf, offset); } static void *get_recv_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->rq.offset + (n << qp->rq.wqe_shift)); } void *mlx5_get_send_wqe(struct mlx5_ib_qp *qp, int n) { return get_wqe(qp, qp->sq.offset + (n << MLX5_IB_SQ_STRIDE)); } /** * mlx5_ib_read_user_wqe() - Copy a user-space WQE to kernel space. * * @qp: QP to copy from. * @send: copy from the send queue when non-zero, use the receive queue * otherwise. * @wqe_index: index to start copying from. For send work queues, the * wqe_index is in units of MLX5_SEND_WQE_BB. * For receive work queue, it is the number of work queue * element in the queue. * @buffer: destination buffer. * @length: maximum number of bytes to copy. * * Copies at least a single WQE, but may copy more data. * * Return: the number of bytes copied, or an error code. */ int mlx5_ib_read_user_wqe(struct mlx5_ib_qp *qp, int send, int wqe_index, void *buffer, u32 length, struct mlx5_ib_qp_base *base) { struct ib_device *ibdev = qp->ibqp.device; struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_wq *wq = send ? &qp->sq : &qp->rq; size_t offset; size_t wq_end; struct ib_umem *umem = base->ubuffer.umem; u32 first_copy_length; int wqe_length; int ret; if (wq->wqe_cnt == 0) { mlx5_ib_dbg(dev, "mlx5_ib_read_user_wqe for a QP with wqe_cnt == 0. qp_type: 0x%x\n", qp->ibqp.qp_type); return -EINVAL; } offset = wq->offset + ((wqe_index % wq->wqe_cnt) << wq->wqe_shift); wq_end = wq->offset + (wq->wqe_cnt << wq->wqe_shift); if (send && length < sizeof(struct mlx5_wqe_ctrl_seg)) return -EINVAL; if (offset > umem->length || (send && offset + sizeof(struct mlx5_wqe_ctrl_seg) > umem->length)) return -EINVAL; first_copy_length = min_t(u32, offset + length, wq_end) - offset; ret = ib_umem_copy_from(buffer, umem, offset, first_copy_length); if (ret) return ret; if (send) { struct mlx5_wqe_ctrl_seg *ctrl = buffer; int ds = be32_to_cpu(ctrl->qpn_ds) & MLX5_WQE_CTRL_DS_MASK; wqe_length = ds * MLX5_WQE_DS_UNITS; } else { wqe_length = 1 << wq->wqe_shift; } if (wqe_length <= first_copy_length) return first_copy_length; ret = ib_umem_copy_from(buffer + first_copy_length, umem, wq->offset, wqe_length - first_copy_length); if (ret) return ret; return wqe_length; } static void mlx5_ib_qp_event(struct mlx5_core_qp *qp, int type) { struct ib_qp *ibqp = &to_mibqp(qp)->ibqp; struct ib_event event; if (type == MLX5_EVENT_TYPE_PATH_MIG) { /* This event is only valid for trans_qps */ to_mibqp(qp)->port = to_mibqp(qp)->trans_qp.alt_port; } if (ibqp->event_handler) { event.device = ibqp->device; event.element.qp = ibqp; switch (type) { case MLX5_EVENT_TYPE_PATH_MIG: event.event = IB_EVENT_PATH_MIG; break; case MLX5_EVENT_TYPE_COMM_EST: event.event = IB_EVENT_COMM_EST; break; case MLX5_EVENT_TYPE_SQ_DRAINED: event.event = IB_EVENT_SQ_DRAINED; break; case MLX5_EVENT_TYPE_SRQ_LAST_WQE: event.event = IB_EVENT_QP_LAST_WQE_REACHED; break; case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_QP_FATAL; break; case MLX5_EVENT_TYPE_PATH_MIG_FAILED: event.event = IB_EVENT_PATH_MIG_ERR; break; case MLX5_EVENT_TYPE_WQ_INVAL_REQ_ERROR: event.event = IB_EVENT_QP_REQ_ERR; break; case MLX5_EVENT_TYPE_WQ_ACCESS_ERROR: event.event = IB_EVENT_QP_ACCESS_ERR; break; default: pr_warn("mlx5_ib: Unexpected event type %d on QP %06x\n", type, qp->qpn); return; } ibqp->event_handler(&event, ibqp->qp_context); } } static int set_rq_size(struct mlx5_ib_dev *dev, struct ib_qp_cap *cap, int has_rq, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd) { int wqe_size; int wq_size; /* Sanity check RQ size before proceeding */ if (cap->max_recv_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) return -EINVAL; if (!has_rq) { qp->rq.max_gs = 0; qp->rq.wqe_cnt = 0; qp->rq.wqe_shift = 0; cap->max_recv_wr = 0; cap->max_recv_sge = 0; } else { if (ucmd) { qp->rq.wqe_cnt = ucmd->rq_wqe_count; if (ucmd->rq_wqe_shift > BITS_PER_BYTE * sizeof(ucmd->rq_wqe_shift)) return -EINVAL; qp->rq.wqe_shift = ucmd->rq_wqe_shift; if ((1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) < qp->wq_sig) return -EINVAL; qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } else { wqe_size = qp->wq_sig ? sizeof(struct mlx5_wqe_signature_seg) : 0; wqe_size += cap->max_recv_sge * sizeof(struct mlx5_wqe_data_seg); wqe_size = roundup_pow_of_two(wqe_size); wq_size = roundup_pow_of_two(cap->max_recv_wr) * wqe_size; wq_size = max_t(int, wq_size, MLX5_SEND_WQE_BB); qp->rq.wqe_cnt = wq_size / wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)) { mlx5_ib_dbg(dev, "wqe_size %d, max %d\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq)); return -EINVAL; } qp->rq.wqe_shift = ilog2(wqe_size); qp->rq.max_gs = (1 << qp->rq.wqe_shift) / sizeof(struct mlx5_wqe_data_seg) - qp->wq_sig; qp->rq.max_post = qp->rq.wqe_cnt; } } return 0; } static int sq_overhead(struct ib_qp_init_attr *attr) { int size = 0; switch (attr->qp_type) { case IB_QPT_XRC_INI: size += sizeof(struct mlx5_wqe_xrc_seg); /* fall through */ case IB_QPT_RC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_atomic_seg) + sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg) + MLX5_IB_SQ_UMR_INLINE_THRESHOLD / MLX5_IB_UMR_OCTOWORD); break; case IB_QPT_XRC_TGT: return 0; case IB_QPT_UC: size += sizeof(struct mlx5_wqe_ctrl_seg) + max(sizeof(struct mlx5_wqe_raddr_seg), sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg)); break; case IB_QPT_UD: if (attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO) size += sizeof(struct mlx5_wqe_eth_pad) + sizeof(struct mlx5_wqe_eth_seg); /* fall through */ case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_datagram_seg); break; case MLX5_IB_QPT_REG_UMR: size += sizeof(struct mlx5_wqe_ctrl_seg) + sizeof(struct mlx5_wqe_umr_ctrl_seg) + sizeof(struct mlx5_mkey_seg); break; default: return -EINVAL; } return size; } static int calc_send_wqe(struct ib_qp_init_attr *attr) { int inl_size = 0; int size; size = sq_overhead(attr); if (size < 0) return size; if (attr->cap.max_inline_data) { inl_size = size + sizeof(struct mlx5_wqe_inline_seg) + attr->cap.max_inline_data; } size += attr->cap.max_send_sge * sizeof(struct mlx5_wqe_data_seg); if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN && ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB) < MLX5_SIG_WQE_SIZE) return MLX5_SIG_WQE_SIZE; else return ALIGN(max_t(int, inl_size, size), MLX5_SEND_WQE_BB); } static int get_send_sge(struct ib_qp_init_attr *attr, int wqe_size) { int max_sge; if (attr->qp_type == IB_QPT_RC) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else if (attr->qp_type == IB_QPT_XRC_INI) max_sge = (min_t(int, wqe_size, 512) - sizeof(struct mlx5_wqe_ctrl_seg) - sizeof(struct mlx5_wqe_xrc_seg) - sizeof(struct mlx5_wqe_raddr_seg)) / sizeof(struct mlx5_wqe_data_seg); else max_sge = (wqe_size - sq_overhead(attr)) / sizeof(struct mlx5_wqe_data_seg); return min_t(int, max_sge, wqe_size - sq_overhead(attr) / sizeof(struct mlx5_wqe_data_seg)); } static int calc_sq_size(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *attr, struct mlx5_ib_qp *qp) { int wqe_size; int wq_size; if (!attr->cap.max_send_wr) return 0; wqe_size = calc_send_wqe(attr); mlx5_ib_dbg(dev, "wqe_size %d\n", wqe_size); if (wqe_size < 0) return wqe_size; if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_dbg(dev, "wqe_size(%d) > max_sq_desc_sz(%d)\n", wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } qp->max_inline_data = wqe_size - sq_overhead(attr) - sizeof(struct mlx5_wqe_inline_seg); attr->cap.max_inline_data = qp->max_inline_data; if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN) qp->signature_en = true; wq_size = roundup_pow_of_two(attr->cap.max_send_wr * wqe_size); qp->sq.wqe_cnt = wq_size / MLX5_SEND_WQE_BB; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_dbg(dev, "send queue size (%d * %d / %d -> %d) exceeds limits(%d)\n", attr->cap.max_send_wr, wqe_size, MLX5_SEND_WQE_BB, qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -ENOMEM; } qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.max_gs = get_send_sge(attr, wqe_size); if (qp->sq.max_gs < attr->cap.max_send_sge) return -ENOMEM; attr->cap.max_send_sge = qp->sq.max_gs; qp->sq.max_post = wq_size / wqe_size; attr->cap.max_send_wr = qp->sq.max_post; return wq_size; } static int set_user_buf_size(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_create_qp *ucmd, struct mlx5_ib_qp_base *base, struct ib_qp_init_attr *attr) { int desc_sz = 1 << qp->sq.wqe_shift; if (desc_sz > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) { mlx5_ib_warn(dev, "desc_sz %d, max_sq_desc_sz %d\n", desc_sz, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)); return -EINVAL; } if (ucmd->sq_wqe_count && ((1 << ilog2(ucmd->sq_wqe_count)) != ucmd->sq_wqe_count)) { mlx5_ib_warn(dev, "sq_wqe_count %d, sq_wqe_count %d\n", ucmd->sq_wqe_count, ucmd->sq_wqe_count); return -EINVAL; } qp->sq.wqe_cnt = ucmd->sq_wqe_count; if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) { mlx5_ib_warn(dev, "wqe_cnt %d, max_wqes %d\n", qp->sq.wqe_cnt, 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz)); return -EINVAL; } if (attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { base->ubuffer.buf_size = qp->rq.wqe_cnt << qp->rq.wqe_shift; qp->raw_packet_qp.sq.ubuffer.buf_size = qp->sq.wqe_cnt << 6; } else { base->ubuffer.buf_size = (qp->rq.wqe_cnt << qp->rq.wqe_shift) + (qp->sq.wqe_cnt << 6); } return 0; } static int qp_has_rq(struct ib_qp_init_attr *attr) { if (attr->qp_type == IB_QPT_XRC_INI || attr->qp_type == IB_QPT_XRC_TGT || attr->srq || attr->qp_type == MLX5_IB_QPT_REG_UMR || !attr->cap.max_recv_wr) return 0; return 1; } enum { /* this is the first blue flame register in the array of bfregs assigned * to a processes. Since we do not use it for blue flame but rather * regular 64 bit doorbells, we do not need a lock for maintaiing * "odd/even" order */ NUM_NON_BLUE_FLAME_BFREGS = 1, }; static int max_bfregs(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return get_num_static_uars(dev, bfregi) * MLX5_NON_FP_BFREGS_PER_UAR; } static int num_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int n; n = max_bfregs(dev, bfregi) - bfregi->num_low_latency_bfregs - NUM_NON_BLUE_FLAME_BFREGS; return n >= 0 ? n : 0; } static int first_med_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { return num_med_bfreg(dev, bfregi) ? 1 : -ENOMEM; } static int first_hi_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int med; med = num_med_bfreg(dev, bfregi); return ++med; } static int alloc_high_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int i; for (i = first_hi_bfreg(dev, bfregi); i < max_bfregs(dev, bfregi); i++) { if (!bfregi->count[i]) { bfregi->count[i]++; return i; } } return -ENOMEM; } static int alloc_med_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int minidx = first_med_bfreg(dev, bfregi); int i; if (minidx < 0) return minidx; for (i = minidx; i < first_hi_bfreg(dev, bfregi); i++) { if (bfregi->count[i] < bfregi->count[minidx]) minidx = i; if (!bfregi->count[minidx]) break; } bfregi->count[minidx]++; return minidx; } static int alloc_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int bfregn = -ENOMEM; mutex_lock(&bfregi->lock); if (bfregi->ver >= 2) { bfregn = alloc_high_class_bfreg(dev, bfregi); if (bfregn < 0) bfregn = alloc_med_class_bfreg(dev, bfregi); } if (bfregn < 0) { BUILD_BUG_ON(NUM_NON_BLUE_FLAME_BFREGS != 1); bfregn = 0; bfregi->count[bfregn]++; } mutex_unlock(&bfregi->lock); return bfregn; } void mlx5_ib_free_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { mutex_lock(&bfregi->lock); bfregi->count[bfregn]--; mutex_unlock(&bfregi->lock); } static enum mlx5_qp_state to_mlx5_state(enum ib_qp_state state) { switch (state) { case IB_QPS_RESET: return MLX5_QP_STATE_RST; case IB_QPS_INIT: return MLX5_QP_STATE_INIT; case IB_QPS_RTR: return MLX5_QP_STATE_RTR; case IB_QPS_RTS: return MLX5_QP_STATE_RTS; case IB_QPS_SQD: return MLX5_QP_STATE_SQD; case IB_QPS_SQE: return MLX5_QP_STATE_SQER; case IB_QPS_ERR: return MLX5_QP_STATE_ERR; default: return -1; } } static int to_mlx5_st(enum ib_qp_type type) { switch (type) { case IB_QPT_RC: return MLX5_QP_ST_RC; case IB_QPT_UC: return MLX5_QP_ST_UC; case IB_QPT_UD: return MLX5_QP_ST_UD; case MLX5_IB_QPT_REG_UMR: return MLX5_QP_ST_REG_UMR; case IB_QPT_XRC_INI: case IB_QPT_XRC_TGT: return MLX5_QP_ST_XRC; case IB_QPT_SMI: return MLX5_QP_ST_QP0; case MLX5_IB_QPT_HW_GSI: return MLX5_QP_ST_QP1; case MLX5_IB_QPT_DCI: return MLX5_QP_ST_DCI; case IB_QPT_RAW_IPV6: return MLX5_QP_ST_RAW_IPV6; case IB_QPT_RAW_PACKET: case IB_QPT_RAW_ETHERTYPE: return MLX5_QP_ST_RAW_ETHERTYPE; case IB_QPT_MAX: default: return -EINVAL; } } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq); int bfregn_to_uar_index(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, u32 bfregn, bool dyn_bfreg) { unsigned int bfregs_per_sys_page; u32 index_of_sys_page; u32 offset; bfregs_per_sys_page = get_uars_per_sys_page(dev, bfregi->lib_uar_4k) * MLX5_NON_FP_BFREGS_PER_UAR; index_of_sys_page = bfregn / bfregs_per_sys_page; if (dyn_bfreg) { index_of_sys_page += bfregi->num_static_sys_pages; if (index_of_sys_page >= bfregi->num_sys_pages) return -EINVAL; if (bfregn > bfregi->num_dyn_bfregs || bfregi->sys_pages[index_of_sys_page] == MLX5_IB_INVALID_UAR_INDEX) { mlx5_ib_dbg(dev, "Invalid dynamic uar index\n"); return -EINVAL; } } offset = bfregn % bfregs_per_sys_page / MLX5_NON_FP_BFREGS_PER_UAR; return bfregi->sys_pages[index_of_sys_page] + offset; } static int mlx5_ib_umem_get(struct mlx5_ib_dev *dev, struct ib_pd *pd, unsigned long addr, size_t size, struct ib_umem **umem, int *npages, int *page_shift, int *ncont, u32 *offset) { int err; *umem = ib_umem_get(pd->uobject->context, addr, size, 0, 0); if (IS_ERR(*umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); return PTR_ERR(*umem); } mlx5_ib_cont_pages(*umem, addr, 0, npages, page_shift, ncont, NULL); err = mlx5_ib_get_buf_offset(addr, *page_shift, offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } mlx5_ib_dbg(dev, "addr 0x%lx, size %zu, npages %d, page_shift %d, ncont %d, offset %d\n", addr, size, *npages, *page_shift, *ncont, *offset); return 0; err_umem: ib_umem_release(*umem); *umem = NULL; return err; } static void destroy_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_ucontext *context; if (rwq->create_flags & MLX5_IB_WQ_FLAGS_DELAY_DROP) atomic_dec(&dev->delay_drop.rqs_cnt); context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &rwq->db); if (rwq->umem) ib_umem_release(rwq->umem); } static int create_user_rq(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_rwq *rwq, struct mlx5_ib_create_wq *ucmd) { struct mlx5_ib_ucontext *context; int page_shift = 0; int npages; u32 offset = 0; int ncont = 0; int err; if (!ucmd->buf_addr) return -EINVAL; context = to_mucontext(pd->uobject->context); rwq->umem = ib_umem_get(pd->uobject->context, ucmd->buf_addr, rwq->buf_size, 0, 0); if (IS_ERR(rwq->umem)) { mlx5_ib_dbg(dev, "umem_get failed\n"); err = PTR_ERR(rwq->umem); return err; } mlx5_ib_cont_pages(rwq->umem, ucmd->buf_addr, 0, &npages, &page_shift, &ncont, NULL); err = mlx5_ib_get_buf_offset(ucmd->buf_addr, page_shift, &rwq->rq_page_offset); if (err) { mlx5_ib_warn(dev, "bad offset\n"); goto err_umem; } rwq->rq_num_pas = ncont; rwq->page_shift = page_shift; rwq->log_page_size = page_shift - MLX5_ADAPTER_PAGE_SHIFT; rwq->wq_sig = !!(ucmd->flags & MLX5_WQ_FLAG_SIGNATURE); mlx5_ib_dbg(dev, "addr 0x%llx, size %zd, npages %d, page_shift %d, ncont %d, offset %d\n", (unsigned long long)ucmd->buf_addr, rwq->buf_size, npages, page_shift, ncont, offset); err = mlx5_ib_db_map_user(context, ucmd->db_addr, &rwq->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_umem; } rwq->create_type = MLX5_WQ_USER; return 0; err_umem: ib_umem_release(rwq->umem); return err; } static int adjust_bfregn(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi, int bfregn) { return bfregn / MLX5_NON_FP_BFREGS_PER_UAR * MLX5_BFREGS_PER_UAR + bfregn % MLX5_NON_FP_BFREGS_PER_UAR; } static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct ib_udata *udata, struct ib_qp_init_attr *attr, u32 **in, struct mlx5_ib_create_qp_resp *resp, int *inlen, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_ubuffer *ubuffer = &base->ubuffer; int page_shift = 0; int uar_index = 0; int npages; u32 offset = 0; int bfregn; int ncont = 0; __be64 *pas; void *qpc; int err; err = ib_copy_from_udata(&ucmd, udata, sizeof(ucmd)); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return err; } context = to_mucontext(pd->uobject->context); if (ucmd.flags & MLX5_QP_FLAG_BFREG_INDEX) { uar_index = bfregn_to_uar_index(dev, &context->bfregi, ucmd.bfreg_index, true); if (uar_index < 0) return uar_index; bfregn = MLX5_IB_INVALID_BFREG; } else if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) { /* * TBD: should come from the verbs when we have the API */ /* In CROSS_CHANNEL CQ and QP must use the same UAR */ bfregn = MLX5_CROSS_CHANNEL_BFREG; } else { bfregn = alloc_bfreg(dev, &context->bfregi); if (bfregn < 0) return bfregn; } mlx5_ib_dbg(dev, "bfregn 0x%x, uar_index 0x%x\n", bfregn, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) uar_index = bfregn_to_uar_index(dev, &context->bfregi, bfregn, false); qp->rq.offset = 0; qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB); qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; err = set_user_buf_size(dev, qp, &ucmd, base, attr); if (err) goto err_bfreg; if (ucmd.buf_addr && ubuffer->buf_size) { ubuffer->buf_addr = ucmd.buf_addr; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &ubuffer->umem, &npages, &page_shift, &ncont, &offset); if (err) goto err_bfreg; } else { ubuffer->umem = NULL; } *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * ncont; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_umem; } pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas); if (ubuffer->umem) mlx5_ib_populate_pas(dev, ubuffer->umem, page_shift, pas, 0); qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, log_page_size, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(qpc, qpc, page_offset, offset); MLX5_SET(qpc, qpc, uar_page, uar_index); if (bfregn != MLX5_IB_INVALID_BFREG) resp->bfreg_index = adjust_bfregn(dev, &context->bfregi, bfregn); else resp->bfreg_index = MLX5_IB_INVALID_BFREG; qp->bfregn = bfregn; err = mlx5_ib_db_map_user(context, ucmd.db_addr, &qp->db); if (err) { mlx5_ib_dbg(dev, "map failed\n"); goto err_free; } err = ib_copy_to_udata(udata, resp, min(udata->outlen, sizeof(*resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); goto err_unmap; } qp->create_type = MLX5_QP_USER; return 0; err_unmap: mlx5_ib_db_unmap_user(context, &qp->db); err_free: kvfree(*in); err_umem: if (ubuffer->umem) ib_umem_release(ubuffer->umem); err_bfreg: if (bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, bfregn); return err; } static void destroy_qp_user(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct mlx5_ib_qp *qp, struct mlx5_ib_qp_base *base) { struct mlx5_ib_ucontext *context; context = to_mucontext(pd->uobject->context); mlx5_ib_db_unmap_user(context, &qp->db); if (base->ubuffer.umem) ib_umem_release(base->ubuffer.umem); /* * Free only the BFREGs which are handled by the kernel. * BFREGs of UARs allocated dynamically are handled by user. */ if (qp->bfregn != MLX5_IB_INVALID_BFREG) mlx5_ib_free_bfreg(dev, &context->bfregi, qp->bfregn); } static int create_kernel_qp(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_qp *qp, u32 **in, int *inlen, struct mlx5_ib_qp_base *base) { int uar_index; void *qpc; int err; if (init_attr->create_flags & ~(IB_QP_CREATE_SIGNATURE_EN | IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK | IB_QP_CREATE_IPOIB_UD_LSO | IB_QP_CREATE_NETIF_QP | mlx5_ib_create_qp_sqpn_qp1())) return -EINVAL; if (init_attr->qp_type == MLX5_IB_QPT_REG_UMR) qp->bf.bfreg = &dev->fp_bfreg; else qp->bf.bfreg = &dev->bfreg; /* We need to divide by two since each register is comprised of * two buffers of identical size, namely odd and even */ qp->bf.buf_size = (1 << MLX5_CAP_GEN(dev->mdev, log_bf_reg_size)) / 2; uar_index = qp->bf.bfreg->index; err = calc_sq_size(dev, init_attr, qp); if (err < 0) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->rq.offset = 0; qp->sq.offset = qp->rq.wqe_cnt << qp->rq.wqe_shift; base->ubuffer.buf_size = err + (qp->rq.wqe_cnt << qp->rq.wqe_shift); err = mlx5_buf_alloc(dev->mdev, base->ubuffer.buf_size, &qp->buf); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } qp->sq.qend = mlx5_get_send_wqe(qp, qp->sq.wqe_cnt); *inlen = MLX5_ST_SZ_BYTES(create_qp_in) + MLX5_FLD_SZ_BYTES(create_qp_in, pas[0]) * qp->buf.npages; *in = kvzalloc(*inlen, GFP_KERNEL); if (!*in) { err = -ENOMEM; goto err_buf; } qpc = MLX5_ADDR_OF(create_qp_in, *in, qpc); MLX5_SET(qpc, qpc, uar_page, uar_index); MLX5_SET(qpc, qpc, log_page_size, qp->buf.page_shift - MLX5_ADAPTER_PAGE_SHIFT); /* Set "fast registration enabled" for all kernel QPs */ MLX5_SET(qpc, qpc, fre, 1); MLX5_SET(qpc, qpc, rlky, 1); if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { MLX5_SET(qpc, qpc, deth_sqpn, 1); qp->flags |= MLX5_IB_QP_SQPN_QP1; } mlx5_fill_page_array(&qp->buf, (__be64 *)MLX5_ADDR_OF(create_qp_in, *in, pas)); err = mlx5_db_alloc(dev->mdev, &qp->db); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); goto err_free; } qp->sq.wrid = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wrid), GFP_KERNEL); qp->sq.wr_data = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wr_data), GFP_KERNEL); qp->rq.wrid = kvmalloc_array(qp->rq.wqe_cnt, sizeof(*qp->rq.wrid), GFP_KERNEL); qp->sq.w_list = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.w_list), GFP_KERNEL); qp->sq.wqe_head = kvmalloc_array(qp->sq.wqe_cnt, sizeof(*qp->sq.wqe_head), GFP_KERNEL); if (!qp->sq.wrid || !qp->sq.wr_data || !qp->rq.wrid || !qp->sq.w_list || !qp->sq.wqe_head) { err = -ENOMEM; goto err_wrid; } qp->create_type = MLX5_QP_KERNEL; return 0; err_wrid: kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); err_free: kvfree(*in); err_buf: mlx5_buf_free(dev->mdev, &qp->buf); return err; } static void destroy_qp_kernel(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { kvfree(qp->sq.wqe_head); kvfree(qp->sq.w_list); kvfree(qp->sq.wrid); kvfree(qp->sq.wr_data); kvfree(qp->rq.wrid); mlx5_db_free(dev->mdev, &qp->db); mlx5_buf_free(dev->mdev, &qp->buf); } static u32 get_rx_type(struct mlx5_ib_qp *qp, struct ib_qp_init_attr *attr) { if (attr->srq || (attr->qp_type == IB_QPT_XRC_TGT) || (attr->qp_type == MLX5_IB_QPT_DCI) || (attr->qp_type == IB_QPT_XRC_INI)) return MLX5_SRQ_RQ; else if (!qp->has_rq) return MLX5_ZERO_LEN_RQ; else return MLX5_NON_ZERO_RQ; } static int is_connected(enum ib_qp_type qp_type) { if (qp_type == IB_QPT_RC || qp_type == IB_QPT_UC) return 1; return 0; } static int create_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct mlx5_ib_sq *sq, u32 tdn) { u32 in[MLX5_ST_SZ_DW(create_tis_in)] = {0}; void *tisc = MLX5_ADDR_OF(create_tis_in, in, ctx); MLX5_SET(tisc, tisc, transport_domain, tdn); if (qp->flags & MLX5_IB_QP_UNDERLAY) MLX5_SET(tisc, tisc, underlay_qpn, qp->underlay_qpn); return mlx5_core_create_tis(dev->mdev, in, sizeof(in), &sq->tisn); } static void destroy_raw_packet_qp_tis(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { mlx5_core_destroy_tis(dev->mdev, sq->tisn); } static void destroy_flow_rule_vport_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { if (sq->flow_rule) mlx5_del_flow_rules(sq->flow_rule); } static int create_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, void *qpin, struct ib_pd *pd) { struct mlx5_ib_ubuffer *ubuffer = &sq->ubuffer; __be64 *pas; void *in; void *sqc; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); void *wq; int inlen; int err; int page_shift = 0; int npages; int ncont = 0; u32 offset = 0; err = mlx5_ib_umem_get(dev, pd, ubuffer->buf_addr, ubuffer->buf_size, &sq->ubuffer.umem, &npages, &page_shift, &ncont, &offset); if (err) return err; inlen = MLX5_ST_SZ_BYTES(create_sq_in) + sizeof(u64) * ncont; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err_umem; } sqc = MLX5_ADDR_OF(create_sq_in, in, ctx); MLX5_SET(sqc, sqc, flush_in_error_en, 1); if (MLX5_CAP_ETH(dev->mdev, multi_pkt_send_wqe)) MLX5_SET(sqc, sqc, allow_multi_pkt_send_wqe, 1); MLX5_SET(sqc, sqc, state, MLX5_SQC_STATE_RST); MLX5_SET(sqc, sqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(sqc, sqc, cqn, MLX5_GET(qpc, qpc, cqn_snd)); MLX5_SET(sqc, sqc, tis_lst_sz, 1); MLX5_SET(sqc, sqc, tis_num_0, sq->tisn); if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, swp)) MLX5_SET(sqc, sqc, allow_swp, 1); wq = MLX5_ADDR_OF(sqc, sqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET(wq, wq, uar_page, MLX5_GET(qpc, qpc, uar_page)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, ilog2(MLX5_SEND_WQE_BB)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_sq_size)); MLX5_SET(wq, wq, log_wq_pg_sz, page_shift - MLX5_ADAPTER_PAGE_SHIFT); MLX5_SET(wq, wq, page_offset, offset); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, sq->ubuffer.umem, page_shift, pas, 0); err = mlx5_core_create_sq_tracked(dev->mdev, in, inlen, &sq->base.mqp); kvfree(in); if (err) goto err_umem; err = create_flow_rule_vport_sq(dev, sq); if (err) goto err_flow; return 0; err_flow: mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); err_umem: ib_umem_release(sq->ubuffer.umem); sq->ubuffer.umem = NULL; return err; } static void destroy_raw_packet_qp_sq(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq) { destroy_flow_rule_vport_sq(dev, sq); mlx5_core_destroy_sq_tracked(dev->mdev, &sq->base.mqp); ib_umem_release(sq->ubuffer.umem); } static size_t get_rq_pas_size(void *qpc) { u32 log_page_size = MLX5_GET(qpc, qpc, log_page_size) + 12; u32 log_rq_stride = MLX5_GET(qpc, qpc, log_rq_stride); u32 log_rq_size = MLX5_GET(qpc, qpc, log_rq_size); u32 page_offset = MLX5_GET(qpc, qpc, page_offset); u32 po_quanta = 1 << (log_page_size - 6); u32 rq_sz = 1 << (log_rq_size + 4 + log_rq_stride); u32 page_size = 1 << log_page_size; u32 rq_sz_po = rq_sz + (page_offset * po_quanta); u32 rq_num_pas = (rq_sz_po + page_size - 1) / page_size; return rq_num_pas * sizeof(u64); } static int create_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, void *qpin, size_t qpinlen) { struct mlx5_ib_qp *mqp = rq->base.container_mibqp; __be64 *pas; __be64 *qp_pas; void *in; void *rqc; void *wq; void *qpc = MLX5_ADDR_OF(create_qp_in, qpin, qpc); size_t rq_pas_size = get_rq_pas_size(qpc); size_t inlen; int err; if (qpinlen < rq_pas_size + MLX5_BYTE_OFF(create_qp_in, pas)) return -EINVAL; inlen = MLX5_ST_SZ_BYTES(create_rq_in) + rq_pas_size; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); if (!(rq->flags & MLX5_IB_RQ_CVLAN_STRIPPING)) MLX5_SET(rqc, rqc, vsd, 1); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); MLX5_SET(rqc, rqc, user_index, MLX5_GET(qpc, qpc, user_index)); MLX5_SET(rqc, rqc, cqn, MLX5_GET(qpc, qpc, cqn_rcv)); if (mqp->flags & MLX5_IB_QP_CAP_SCATTER_FCS) MLX5_SET(rqc, rqc, scatter_fcs, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, MLX5_WQ_TYPE_CYCLIC); if (rq->flags & MLX5_IB_RQ_PCI_WRITE_END_PADDING) MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); MLX5_SET(wq, wq, page_offset, MLX5_GET(qpc, qpc, page_offset)); MLX5_SET(wq, wq, pd, MLX5_GET(qpc, qpc, pd)); MLX5_SET64(wq, wq, dbr_addr, MLX5_GET64(qpc, qpc, dbr_addr)); MLX5_SET(wq, wq, log_wq_stride, MLX5_GET(qpc, qpc, log_rq_stride) + 4); MLX5_SET(wq, wq, log_wq_pg_sz, MLX5_GET(qpc, qpc, log_page_size)); MLX5_SET(wq, wq, log_wq_sz, MLX5_GET(qpc, qpc, log_rq_size)); pas = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); qp_pas = (__be64 *)MLX5_ADDR_OF(create_qp_in, qpin, pas); memcpy(pas, qp_pas, rq_pas_size); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rq->base.mqp); kvfree(in); return err; } static void destroy_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_rq_tracked(dev->mdev, &rq->base.mqp); } static bool tunnel_offload_supported(struct mlx5_core_dev *dev) { return (MLX5_CAP_ETH(dev, tunnel_stateless_vxlan) || MLX5_CAP_ETH(dev, tunnel_stateless_gre) || MLX5_CAP_ETH(dev, tunnel_stateless_geneve_rx)); } static int create_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u32 tdn, bool tunnel_offload_en) { u32 *in; void *tirc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_DIRECT); MLX5_SET(tirc, tirc, inline_rqn, rq->base.mqp.qpn); MLX5_SET(tirc, tirc, transport_domain, tdn); if (tunnel_offload_en) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &rq->tirn); kvfree(in); return err; } static void destroy_raw_packet_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq) { mlx5_core_destroy_tir(dev->mdev, rq->tirn); } static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u32 *in, size_t inlen, struct ib_pd *pd) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); int err; u32 tdn = mucontext->tdn; if (qp->sq.wqe_cnt) { err = create_raw_packet_qp_tis(dev, qp, sq, tdn); if (err) return err; err = create_raw_packet_qp_sq(dev, sq, in, pd); if (err) goto err_destroy_tis; sq->base.container_mibqp = qp; sq->base.mqp.event = mlx5_ib_qp_event; } if (qp->rq.wqe_cnt) { rq->base.container_mibqp = qp; if (qp->flags & MLX5_IB_QP_CVLAN_STRIPPING) rq->flags |= MLX5_IB_RQ_CVLAN_STRIPPING; if (qp->flags & MLX5_IB_QP_PCI_WRITE_END_PADDING) rq->flags |= MLX5_IB_RQ_PCI_WRITE_END_PADDING; err = create_raw_packet_qp_rq(dev, rq, in, inlen); if (err) goto err_destroy_sq; err = create_raw_packet_qp_tir(dev, rq, tdn, qp->tunnel_offload_en); if (err) goto err_destroy_rq; } qp->trans_qp.base.mqp.qpn = qp->sq.wqe_cnt ? sq->base.mqp.qpn : rq->base.mqp.qpn; return 0; err_destroy_rq: destroy_raw_packet_qp_rq(dev, rq); err_destroy_sq: if (!qp->sq.wqe_cnt) return err; destroy_raw_packet_qp_sq(dev, sq); err_destroy_tis: destroy_raw_packet_qp_tis(dev, sq); return err; } static void destroy_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; if (qp->rq.wqe_cnt) { destroy_raw_packet_qp_tir(dev, rq); destroy_raw_packet_qp_rq(dev, rq); } if (qp->sq.wqe_cnt) { destroy_raw_packet_qp_sq(dev, sq); destroy_raw_packet_qp_tis(dev, sq); } } static void raw_packet_qp_copy_info(struct mlx5_ib_qp *qp, struct mlx5_ib_raw_packet_qp *raw_packet_qp) { struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; sq->sq = &qp->sq; rq->rq = &qp->rq; sq->doorbell = &qp->db; rq->doorbell = &qp->db; } static void destroy_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { mlx5_core_destroy_tir(dev->mdev, qp->rss_qp.tirn); } static int create_rss_raw_qp_tir(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata) { struct ib_uobject *uobj = pd->uobject; struct ib_ucontext *ucontext = uobj->context; struct mlx5_ib_ucontext *mucontext = to_mucontext(ucontext); struct mlx5_ib_create_qp_resp resp = {}; int inlen; int err; u32 *in; void *tirc; void *hfso; u32 selected_fields = 0; u32 outer_l4; size_t min_resp_len; u32 tdn = mucontext->tdn; struct mlx5_ib_create_qp_rss ucmd = {}; size_t required_cmd_sz; if (init_attr->qp_type != IB_QPT_RAW_PACKET) return -EOPNOTSUPP; if (init_attr->create_flags || init_attr->send_cq) return -EINVAL; min_resp_len = offsetof(typeof(resp), bfreg_index) + sizeof(resp.bfreg_index); if (udata->outlen < min_resp_len) return -EINVAL; required_cmd_sz = offsetof(typeof(ucmd), flags) + sizeof(ucmd.flags); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } if (ucmd.flags & ~MLX5_QP_FLAG_TUNNEL_OFFLOADS) { mlx5_ib_dbg(dev, "invalid flags\n"); return -EOPNOTSUPP; } if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS && !tunnel_offload_supported(dev->mdev)) { mlx5_ib_dbg(dev, "tunnel offloads isn't supported\n"); return -EOPNOTSUPP; } if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER && !(ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS)) { mlx5_ib_dbg(dev, "Tunnel offloads must be set for inner RSS\n"); return -EOPNOTSUPP; } err = ib_copy_to_udata(udata, &resp, min(udata->outlen, sizeof(resp))); if (err) { mlx5_ib_dbg(dev, "copy failed\n"); return -EINVAL; } inlen = MLX5_ST_SZ_BYTES(create_tir_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; tirc = MLX5_ADDR_OF(create_tir_in, in, ctx); MLX5_SET(tirc, tirc, disp_type, MLX5_TIRC_DISP_TYPE_INDIRECT); MLX5_SET(tirc, tirc, indirect_table, init_attr->rwq_ind_tbl->ind_tbl_num); MLX5_SET(tirc, tirc, transport_domain, tdn); hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) MLX5_SET(tirc, tirc, tunneled_offload_en, 1); if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_INNER) hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_inner); else hfso = MLX5_ADDR_OF(tirc, tirc, rx_hash_field_selector_outer); switch (ucmd.rx_hash_function) { case MLX5_RX_HASH_FUNC_TOEPLITZ: { void *rss_key = MLX5_ADDR_OF(tirc, tirc, rx_hash_toeplitz_key); size_t len = MLX5_FLD_SZ_BYTES(tirc, rx_hash_toeplitz_key); if (len != ucmd.rx_key_len) { err = -EINVAL; goto err; } MLX5_SET(tirc, tirc, rx_hash_fn, MLX5_RX_HASH_FN_TOEPLITZ); MLX5_SET(tirc, tirc, rx_hash_symmetric, 1); memcpy(rss_key, ucmd.rx_hash_key, len); break; } default: err = -EOPNOTSUPP; goto err; } if (!ucmd.rx_hash_fields_mask) { /* special case when this TIR serves as steering entry without hashing */ if (!init_attr->rwq_ind_tbl->log_ind_tbl_size) goto create_tir; err = -EINVAL; goto err; } if (((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) && ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6))) { err = -EINVAL; goto err; } /* If none of IPV4 & IPV6 SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV4); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) MLX5_SET(rx_hash_field_select, hfso, l3_prot_type, MLX5_L3_PROT_TYPE_IPV6); outer_l4 = ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) << 0 | ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) << 1 | (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) << 2; /* Check that only one l4 protocol is set */ if (outer_l4 & (outer_l4 - 1)) { err = -EINVAL; goto err; } /* If none of TCP & UDP SRC/DST was set - this bit field is ignored */ if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_TCP); else if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) MLX5_SET(rx_hash_field_select, hfso, l4_prot_type, MLX5_L4_PROT_TYPE_UDP); if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_SRC_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV4) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_IPV6)) selected_fields |= MLX5_HASH_FIELD_SEL_DST_IP; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_SRC_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_SPORT; if ((ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_TCP) || (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_DST_PORT_UDP)) selected_fields |= MLX5_HASH_FIELD_SEL_L4_DPORT; if (ucmd.rx_hash_fields_mask & MLX5_RX_HASH_IPSEC_SPI) selected_fields |= MLX5_HASH_FIELD_SEL_IPSEC_SPI; MLX5_SET(rx_hash_field_select, hfso, selected_fields, selected_fields); create_tir: if (dev->rep) MLX5_SET(tirc, tirc, self_lb_block, MLX5_TIRC_SELF_LB_BLOCK_BLOCK_UNICAST_); err = mlx5_core_create_tir(dev->mdev, in, inlen, &qp->rss_qp.tirn); if (err) goto err; kvfree(in); /* qpn is reserved for that QP */ qp->trans_qp.base.mqp.qpn = 0; qp->flags |= MLX5_IB_QP_RSS; return 0; err: kvfree(in); return err; } static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp = {}; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; } static void mlx5_ib_lock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __acquires(&send_cq->lock) __acquires(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); spin_lock_nested(&recv_cq->lock, SINGLE_DEPTH_NESTING); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } else { spin_lock(&recv_cq->lock); spin_lock_nested(&send_cq->lock, SINGLE_DEPTH_NESTING); } } else { spin_lock(&send_cq->lock); __acquire(&recv_cq->lock); } } else if (recv_cq) { spin_lock(&recv_cq->lock); __acquire(&send_cq->lock); } else { __acquire(&send_cq->lock); __acquire(&recv_cq->lock); } } static void mlx5_ib_unlock_cqs(struct mlx5_ib_cq *send_cq, struct mlx5_ib_cq *recv_cq) __releases(&send_cq->lock) __releases(&recv_cq->lock) { if (send_cq) { if (recv_cq) { if (send_cq->mcq.cqn < recv_cq->mcq.cqn) { spin_unlock(&recv_cq->lock); spin_unlock(&send_cq->lock); } else if (send_cq->mcq.cqn == recv_cq->mcq.cqn) { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } else { spin_unlock(&send_cq->lock); spin_unlock(&recv_cq->lock); } } else { __release(&recv_cq->lock); spin_unlock(&send_cq->lock); } } else if (recv_cq) { __release(&send_cq->lock); spin_unlock(&recv_cq->lock); } else { __release(&recv_cq->lock); __release(&send_cq->lock); } } static struct mlx5_ib_pd *get_pd(struct mlx5_ib_qp *qp) { return to_mpd(qp->ibqp.pd); } static void get_cqs(enum ib_qp_type qp_type, struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq, struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq) { switch (qp_type) { case IB_QPT_XRC_TGT: *send_cq = NULL; *recv_cq = NULL; break; case MLX5_IB_QPT_REG_UMR: case IB_QPT_XRC_INI: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = NULL; break; case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_RAW_PACKET: *send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL; *recv_cq = ib_recv_cq ? to_mcq(ib_recv_cq) : NULL; break; case IB_QPT_MAX: default: *send_cq = NULL; *recv_cq = NULL; break; } } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 lag_tx_affinity); static void destroy_qp_common(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp) { struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_ib_qp_base *base; unsigned long flags; int err; if (qp->ibqp.rwq_ind_tbl) { destroy_rss_raw_qp_tir(dev, qp); return; } base = (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; if (qp->state != IB_QPS_RESET) { if (qp->ibqp.qp_type != IB_QPT_RAW_PACKET && !(qp->flags & MLX5_IB_QP_UNDERLAY)) { err = mlx5_core_qp_modify(dev->mdev, MLX5_CMD_OP_2RST_QP, 0, NULL, &base->mqp); } else { struct mlx5_modify_raw_qp_param raw_qp_param = { .operation = MLX5_CMD_OP_2RST_QP }; err = modify_raw_packet_qp(dev, qp, &raw_qp_param, 0); } if (err) mlx5_ib_warn(dev, "mlx5_ib: modify QP 0x%06x to RESET failed\n", base->mqp.qpn); } get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* del from lists under both locks above to protect reset flow paths */ list_del(&qp->qps_list); if (send_cq) list_del(&qp->cq_send_list); if (recv_cq) list_del(&qp->cq_recv_list); if (qp->create_type == MLX5_QP_KERNEL) { __mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, qp->ibqp.srq ? to_msrq(qp->ibqp.srq) : NULL); if (send_cq != recv_cq) __mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); } mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { destroy_raw_packet_qp(dev, qp); } else { err = mlx5_core_destroy_qp(dev->mdev, &base->mqp); if (err) mlx5_ib_warn(dev, "failed to destroy QP 0x%x\n", base->mqp.qpn); } if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); else if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, &get_pd(qp)->ibpd, qp, base); } static const char *ib_qp_type_str(enum ib_qp_type type) { switch (type) { case IB_QPT_SMI: return "IB_QPT_SMI"; case IB_QPT_GSI: return "IB_QPT_GSI"; case IB_QPT_RC: return "IB_QPT_RC"; case IB_QPT_UC: return "IB_QPT_UC"; case IB_QPT_UD: return "IB_QPT_UD"; case IB_QPT_RAW_IPV6: return "IB_QPT_RAW_IPV6"; case IB_QPT_RAW_ETHERTYPE: return "IB_QPT_RAW_ETHERTYPE"; case IB_QPT_XRC_INI: return "IB_QPT_XRC_INI"; case IB_QPT_XRC_TGT: return "IB_QPT_XRC_TGT"; case IB_QPT_RAW_PACKET: return "IB_QPT_RAW_PACKET"; case MLX5_IB_QPT_REG_UMR: return "MLX5_IB_QPT_REG_UMR"; case IB_QPT_DRIVER: return "IB_QPT_DRIVER"; case IB_QPT_MAX: default: return "Invalid QP type"; } } static struct ib_qp *mlx5_ib_create_dct(struct ib_pd *pd, struct ib_qp_init_attr *attr, struct mlx5_ib_create_qp *ucmd) { struct mlx5_ib_qp *qp; int err = 0; u32 uidx = MLX5_IB_DEFAULT_UIDX; void *dctc; if (!attr->srq || !attr->recv_cq) return ERR_PTR(-EINVAL); err = get_qp_user_index(to_mucontext(pd->uobject->context), ucmd, sizeof(*ucmd), &uidx); if (err) return ERR_PTR(err); qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); qp->dct.in = kzalloc(MLX5_ST_SZ_BYTES(create_dct_in), GFP_KERNEL); if (!qp->dct.in) { err = -ENOMEM; goto err_free; } dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); qp->qp_sub_type = MLX5_IB_QPT_DCT; MLX5_SET(dctc, dctc, pd, to_mpd(pd)->pdn); MLX5_SET(dctc, dctc, srqn_xrqn, to_msrq(attr->srq)->msrq.srqn); MLX5_SET(dctc, dctc, cqn, to_mcq(attr->recv_cq)->mcq.cqn); MLX5_SET64(dctc, dctc, dc_access_key, ucmd->access_key); MLX5_SET(dctc, dctc, user_index, uidx); qp->state = IB_QPS_RESET; return &qp->ibqp; err_free: kfree(qp); return ERR_PTR(err); } static int set_mlx_qp_type(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *init_attr, struct mlx5_ib_create_qp *ucmd, struct ib_udata *udata) { enum { MLX_QP_FLAGS = MLX5_QP_FLAG_TYPE_DCT | MLX5_QP_FLAG_TYPE_DCI }; int err; if (!udata) return -EINVAL; if (udata->inlen < sizeof(*ucmd)) { mlx5_ib_dbg(dev, "create_qp user command is smaller than expected\n"); return -EINVAL; } err = ib_copy_from_udata(ucmd, udata, sizeof(*ucmd)); if (err) return err; if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCI) { init_attr->qp_type = MLX5_IB_QPT_DCI; } else { if ((ucmd->flags & MLX_QP_FLAGS) == MLX5_QP_FLAG_TYPE_DCT) { init_attr->qp_type = MLX5_IB_QPT_DCT; } else { mlx5_ib_dbg(dev, "Invalid QP flags\n"); return -EINVAL; } } if (!MLX5_CAP_GEN(dev->mdev, dct)) { mlx5_ib_dbg(dev, "DC transport is not supported\n"); return -EOPNOTSUPP; } return 0; } struct ib_qp *mlx5_ib_create_qp(struct ib_pd *pd, struct ib_qp_init_attr *verbs_init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_qp *qp; u16 xrcdn = 0; int err; struct ib_qp_init_attr mlx_init_attr; struct ib_qp_init_attr *init_attr = verbs_init_attr; if (pd) { dev = to_mdev(pd->device); if (init_attr->qp_type == IB_QPT_RAW_PACKET) { if (!pd->uobject) { mlx5_ib_dbg(dev, "Raw Packet QP is not supported for kernel consumers\n"); return ERR_PTR(-EINVAL); } else if (!to_mucontext(pd->uobject->context)->cqe_version) { mlx5_ib_dbg(dev, "Raw Packet QP is only supported for CQE version > 0\n"); return ERR_PTR(-EINVAL); } } } else { /* being cautious here */ if (init_attr->qp_type != IB_QPT_XRC_TGT && init_attr->qp_type != MLX5_IB_QPT_REG_UMR) { pr_warn("%s: no PD for transport %s\n", __func__, ib_qp_type_str(init_attr->qp_type)); return ERR_PTR(-EINVAL); } dev = to_mdev(to_mxrcd(init_attr->xrcd)->ibxrcd.device); } if (init_attr->qp_type == IB_QPT_DRIVER) { struct mlx5_ib_create_qp ucmd; init_attr = &mlx_init_attr; memcpy(init_attr, verbs_init_attr, sizeof(*verbs_init_attr)); err = set_mlx_qp_type(dev, init_attr, &ucmd, udata); if (err) return ERR_PTR(err); if (init_attr->qp_type == MLX5_IB_QPT_DCI) { if (init_attr->cap.max_recv_wr || init_attr->cap.max_recv_sge) { mlx5_ib_dbg(dev, "DCI QP requires zero size receive queue\n"); return ERR_PTR(-EINVAL); } } else { return mlx5_ib_create_dct(pd, init_attr, &ucmd); } } switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: case IB_QPT_XRC_INI: if (!MLX5_CAP_GEN(dev->mdev, xrc)) { mlx5_ib_dbg(dev, "XRC not supported\n"); return ERR_PTR(-ENOSYS); } init_attr->recv_cq = NULL; if (init_attr->qp_type == IB_QPT_XRC_TGT) { xrcdn = to_mxrcd(init_attr->xrcd)->xrcdn; init_attr->send_cq = NULL; } /* fall through */ case IB_QPT_RAW_PACKET: case IB_QPT_RC: case IB_QPT_UC: case IB_QPT_UD: case IB_QPT_SMI: case MLX5_IB_QPT_HW_GSI: case MLX5_IB_QPT_REG_UMR: case MLX5_IB_QPT_DCI: qp = kzalloc(sizeof(*qp), GFP_KERNEL); if (!qp) return ERR_PTR(-ENOMEM); err = create_qp_common(dev, pd, init_attr, udata, qp); if (err) { mlx5_ib_dbg(dev, "create_qp_common failed\n"); kfree(qp); return ERR_PTR(err); } if (is_qp0(init_attr->qp_type)) qp->ibqp.qp_num = 0; else if (is_qp1(init_attr->qp_type)) qp->ibqp.qp_num = 1; else qp->ibqp.qp_num = qp->trans_qp.base.mqp.qpn; mlx5_ib_dbg(dev, "ib qpnum 0x%x, mlx qpn 0x%x, rcqn 0x%x, scqn 0x%x\n", qp->ibqp.qp_num, qp->trans_qp.base.mqp.qpn, init_attr->recv_cq ? to_mcq(init_attr->recv_cq)->mcq.cqn : -1, init_attr->send_cq ? to_mcq(init_attr->send_cq)->mcq.cqn : -1); qp->trans_qp.xrcdn = xrcdn; break; case IB_QPT_GSI: return mlx5_ib_gsi_create_qp(pd, init_attr); case IB_QPT_RAW_IPV6: case IB_QPT_RAW_ETHERTYPE: case IB_QPT_MAX: default: mlx5_ib_dbg(dev, "unsupported qp type %d\n", init_attr->qp_type); /* Don't support raw QPs */ return ERR_PTR(-EINVAL); } if (verbs_init_attr->qp_type == IB_QPT_DRIVER) qp->qp_sub_type = init_attr->qp_type; return &qp->ibqp; } static int mlx5_ib_destroy_dct(struct mlx5_ib_qp *mqp) { struct mlx5_ib_dev *dev = to_mdev(mqp->ibqp.device); if (mqp->state == IB_QPS_RTR) { int err; err = mlx5_core_destroy_dct(dev->mdev, &mqp->dct.mdct); if (err) { mlx5_ib_warn(dev, "failed to destroy DCT %d\n", err); return err; } } kfree(mqp->dct.in); kfree(mqp); return 0; } int mlx5_ib_destroy_qp(struct ib_qp *qp) { struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_ib_qp *mqp = to_mqp(qp); if (unlikely(qp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_destroy_qp(qp); if (mqp->qp_sub_type == MLX5_IB_QPT_DCT) return mlx5_ib_destroy_dct(mqp); destroy_qp_common(dev, mqp); kfree(mqp); return 0; } static __be32 to_mlx5_access_flags(struct mlx5_ib_qp *qp, const struct ib_qp_attr *attr, int attr_mask) { u32 hw_access_flags = 0; u8 dest_rd_atomic; u32 access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) dest_rd_atomic = attr->max_dest_rd_atomic; else dest_rd_atomic = qp->trans_qp.resp_depth; if (attr_mask & IB_QP_ACCESS_FLAGS) access_flags = attr->qp_access_flags; else access_flags = qp->trans_qp.atomic_rd_en; if (!dest_rd_atomic) access_flags &= IB_ACCESS_REMOTE_WRITE; if (access_flags & IB_ACCESS_REMOTE_READ) hw_access_flags |= MLX5_QP_BIT_RRE; if (access_flags & IB_ACCESS_REMOTE_ATOMIC) hw_access_flags |= (MLX5_QP_BIT_RAE | MLX5_ATOMIC_MODE_CX); if (access_flags & IB_ACCESS_REMOTE_WRITE) hw_access_flags |= MLX5_QP_BIT_RWE; return cpu_to_be32(hw_access_flags); } enum { MLX5_PATH_FLAG_FL = 1 << 0, MLX5_PATH_FLAG_FREE_AR = 1 << 1, MLX5_PATH_FLAG_COUNTER = 1 << 2, }; static int ib_rate_to_mlx5(struct mlx5_ib_dev *dev, u8 rate) { if (rate == IB_RATE_PORT_CURRENT) return 0; if (rate < IB_RATE_2_5_GBPS || rate > IB_RATE_300_GBPS) return -EINVAL; while (rate != IB_RATE_PORT_CURRENT && !(1 << (rate + MLX5_STAT_RATE_OFFSET) & MLX5_CAP_GEN(dev->mdev, stat_rate_support))) --rate; return rate ? rate + MLX5_STAT_RATE_OFFSET : rate; } static int modify_raw_packet_eth_prio(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 sl) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.prio, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, prio, ((sl & 0x7) << 1)); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int modify_raw_packet_tx_affinity(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, u8 tx_affinity) { void *in; void *tisc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_tis_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_tis_in, in, bitmask.lag_tx_port_affinity, 1); tisc = MLX5_ADDR_OF(modify_tis_in, in, ctx); MLX5_SET(tisc, tisc, lag_tx_port_affinity, tx_affinity); err = mlx5_core_modify_tis(dev, sq->tisn, in, inlen); kvfree(in); return err; } static int mlx5_set_path(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct rdma_ah_attr *ah, struct mlx5_qp_path *path, u8 port, int attr_mask, u32 path_flags, const struct ib_qp_attr *attr, bool alt) { const struct ib_global_route *grh = rdma_ah_read_grh(ah); int err; enum ib_gid_type gid_type; u8 ah_flags = rdma_ah_get_ah_flags(ah); u8 sl = rdma_ah_get_sl(ah); if (attr_mask & IB_QP_PKEY_INDEX) path->pkey_index = cpu_to_be16(alt ? attr->alt_pkey_index : attr->pkey_index); if (ah_flags & IB_AH_GRH) { if (grh->sgid_index >= dev->mdev->port_caps[port - 1].gid_table_len) { pr_err("sgid_index (%u) too large. max is %d\n", grh->sgid_index, dev->mdev->port_caps[port - 1].gid_table_len); return -EINVAL; } } if (ah->type == RDMA_AH_ATTR_TYPE_ROCE) { if (!(ah_flags & IB_AH_GRH)) return -EINVAL; memcpy(path->rmac, ah->roce.dmac, sizeof(ah->roce.dmac)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC || qp->ibqp.qp_type == IB_QPT_XRC_INI || qp->ibqp.qp_type == IB_QPT_XRC_TGT) path->udp_sport = mlx5_get_roce_udp_sport(dev, ah->grh.sgid_attr); path->dci_cfi_prio_sl = (sl & 0x7) << 4; gid_type = ah->grh.sgid_attr->gid_type; if (gid_type == IB_GID_TYPE_ROCE_UDP_ENCAP) path->ecn_dscp = (grh->traffic_class >> 2) & 0x3f; } else { path->fl_free_ar = (path_flags & MLX5_PATH_FLAG_FL) ? 0x80 : 0; path->fl_free_ar |= (path_flags & MLX5_PATH_FLAG_FREE_AR) ? 0x40 : 0; path->rlid = cpu_to_be16(rdma_ah_get_dlid(ah)); path->grh_mlid = rdma_ah_get_path_bits(ah) & 0x7f; if (ah_flags & IB_AH_GRH) path->grh_mlid |= 1 << 7; path->dci_cfi_prio_sl = sl & 0xf; } if (ah_flags & IB_AH_GRH) { path->mgid_index = grh->sgid_index; path->hop_limit = grh->hop_limit; path->tclass_flowlabel = cpu_to_be32((grh->traffic_class << 20) | (grh->flow_label)); memcpy(path->rgid, grh->dgid.raw, 16); } err = ib_rate_to_mlx5(dev, rdma_ah_get_static_rate(ah)); if (err < 0) return err; path->static_rate = err; path->port = port; if (attr_mask & IB_QP_TIMEOUT) path->ackto_lt = (alt ? attr->alt_timeout : attr->timeout) << 3; if ((qp->ibqp.qp_type == IB_QPT_RAW_PACKET) && qp->sq.wqe_cnt) return modify_raw_packet_eth_prio(dev->mdev, &qp->raw_packet_qp.sq, sl & 0xf); return 0; } static enum mlx5_qp_optpar opt_mask[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE][MLX5_QP_ST_MAX] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_INIT] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_PRI_PORT, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_PRI_PORT, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_PKEY_INDEX | MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_XRC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PKEY_INDEX, }, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_RNR_TIMEOUT, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_ALT_ADDR_PATH | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, }, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_PM_STATE | MLX5_QP_OPTPAR_ALT_ADDR_PATH, [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY | MLX5_QP_OPTPAR_SRQN | MLX5_QP_OPTPAR_CQN_RCV, }, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RTS] = { [MLX5_QP_ST_UD] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_MLX] = MLX5_QP_OPTPAR_Q_KEY, [MLX5_QP_ST_UC] = MLX5_QP_OPTPAR_RWE, [MLX5_QP_ST_RC] = MLX5_QP_OPTPAR_RNR_TIMEOUT | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RAE | MLX5_QP_OPTPAR_RRE, }, }, }; static int ib_nr_to_mlx5_nr(int ib_mask) { switch (ib_mask) { case IB_QP_STATE: return 0; case IB_QP_CUR_STATE: return 0; case IB_QP_EN_SQD_ASYNC_NOTIFY: return 0; case IB_QP_ACCESS_FLAGS: return MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PKEY_INDEX: return MLX5_QP_OPTPAR_PKEY_INDEX; case IB_QP_PORT: return MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_QKEY: return MLX5_QP_OPTPAR_Q_KEY; case IB_QP_AV: return MLX5_QP_OPTPAR_PRIMARY_ADDR_PATH | MLX5_QP_OPTPAR_PRI_PORT; case IB_QP_PATH_MTU: return 0; case IB_QP_TIMEOUT: return MLX5_QP_OPTPAR_ACK_TIMEOUT; case IB_QP_RETRY_CNT: return MLX5_QP_OPTPAR_RETRY_COUNT; case IB_QP_RNR_RETRY: return MLX5_QP_OPTPAR_RNR_RETRY; case IB_QP_RQ_PSN: return 0; case IB_QP_MAX_QP_RD_ATOMIC: return MLX5_QP_OPTPAR_SRA_MAX; case IB_QP_ALT_PATH: return MLX5_QP_OPTPAR_ALT_ADDR_PATH; case IB_QP_MIN_RNR_TIMER: return MLX5_QP_OPTPAR_RNR_TIMEOUT; case IB_QP_SQ_PSN: return 0; case IB_QP_MAX_DEST_RD_ATOMIC: return MLX5_QP_OPTPAR_RRA_MAX | MLX5_QP_OPTPAR_RWE | MLX5_QP_OPTPAR_RRE | MLX5_QP_OPTPAR_RAE; case IB_QP_PATH_MIG_STATE: return MLX5_QP_OPTPAR_PM_STATE; case IB_QP_CAP: return 0; case IB_QP_DEST_QPN: return 0; } return 0; } static int ib_mask_to_mlx5_opt(int ib_mask) { int result = 0; int i; for (i = 0; i < 8 * sizeof(int); i++) { if ((1 << i) & ib_mask) result |= ib_nr_to_mlx5_nr(1 << i); } return result; } static int modify_raw_packet_qp_rq(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { void *in; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_rq_in, in, rq_state, rq->state); rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); MLX5_SET(rqc, rqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, raw_qp_param->rq_q_ctr_id); } else pr_info_once("%s: RAW PACKET QP counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rq->base.mqp.qpn, in, inlen); if (err) goto out; rq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp_sq(struct mlx5_core_dev *dev, struct mlx5_ib_sq *sq, int new_state, const struct mlx5_modify_raw_qp_param *raw_qp_param) { struct mlx5_ib_qp *ibqp = sq->base.container_mibqp; struct mlx5_rate_limit old_rl = ibqp->rl; struct mlx5_rate_limit new_rl = old_rl; bool new_rate_added = false; u16 rl_index = 0; void *in; void *sqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(modify_sq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; MLX5_SET(modify_sq_in, in, sq_state, sq->state); sqc = MLX5_ADDR_OF(modify_sq_in, in, ctx); MLX5_SET(sqc, sqc, state, new_state); if (raw_qp_param->set_mask & MLX5_RAW_QP_RATE_LIMIT) { if (new_state != MLX5_SQC_STATE_RDY) pr_warn("%s: Rate limit can only be changed when SQ is moving to RDY\n", __func__); else new_rl = raw_qp_param->rl; } if (!mlx5_rl_are_equal(&old_rl, &new_rl)) { if (new_rl.rate) { err = mlx5_rl_add_rate(dev, &rl_index, &new_rl); if (err) { pr_err("Failed configuring rate limit(err %d): \ rate %u, max_burst_sz %u, typical_pkt_sz %u\n", err, new_rl.rate, new_rl.max_burst_sz, new_rl.typical_pkt_sz); goto out; } new_rate_added = true; } MLX5_SET64(modify_sq_in, in, modify_bitmask, 1); /* index 0 means no limit */ MLX5_SET(sqc, sqc, packet_pacing_rate_limit_index, rl_index); } err = mlx5_core_modify_sq(dev, sq->base.mqp.qpn, in, inlen); if (err) { /* Remove new rate from table if failed */ if (new_rate_added) mlx5_rl_remove_rate(dev, &new_rl); goto out; } /* Only remove the old rate after new rate was set */ if ((old_rl.rate && !mlx5_rl_are_equal(&old_rl, &new_rl)) || (new_state != MLX5_SQC_STATE_RDY)) mlx5_rl_remove_rate(dev, &old_rl); ibqp->rl = new_rl; sq->state = new_state; out: kvfree(in); return err; } static int modify_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, const struct mlx5_modify_raw_qp_param *raw_qp_param, u8 tx_affinity) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; int modify_rq = !!qp->rq.wqe_cnt; int modify_sq = !!qp->sq.wqe_cnt; int rq_state; int sq_state; int err; switch (raw_qp_param->operation) { case MLX5_CMD_OP_RST2INIT_QP: rq_state = MLX5_RQC_STATE_RDY; sq_state = MLX5_SQC_STATE_RDY; break; case MLX5_CMD_OP_2ERR_QP: rq_state = MLX5_RQC_STATE_ERR; sq_state = MLX5_SQC_STATE_ERR; break; case MLX5_CMD_OP_2RST_QP: rq_state = MLX5_RQC_STATE_RST; sq_state = MLX5_SQC_STATE_RST; break; case MLX5_CMD_OP_RTR2RTS_QP: case MLX5_CMD_OP_RTS2RTS_QP: if (raw_qp_param->set_mask == MLX5_RAW_QP_RATE_LIMIT) { modify_rq = 0; sq_state = sq->state; } else { return raw_qp_param->set_mask ? -EINVAL : 0; } break; case MLX5_CMD_OP_INIT2INIT_QP: case MLX5_CMD_OP_INIT2RTR_QP: if (raw_qp_param->set_mask) return -EINVAL; else return 0; default: WARN_ON(1); return -EINVAL; } if (modify_rq) { err = modify_raw_packet_qp_rq(dev, rq, rq_state, raw_qp_param); if (err) return err; } if (modify_sq) { if (tx_affinity) { err = modify_raw_packet_tx_affinity(dev->mdev, sq, tx_affinity); if (err) return err; } return modify_raw_packet_qp_sq(dev->mdev, sq, sq_state, raw_qp_param); } return 0; } static int __mlx5_ib_modify_qp(struct ib_qp *ibqp, const struct ib_qp_attr *attr, int attr_mask, enum ib_qp_state cur_state, enum ib_qp_state new_state, const struct mlx5_ib_modify_qp *ucmd) { static const u16 optab[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE] = { [MLX5_QP_STATE_RST] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_RST2INIT_QP, }, [MLX5_QP_STATE_INIT] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_INIT] = MLX5_CMD_OP_INIT2INIT_QP, [MLX5_QP_STATE_RTR] = MLX5_CMD_OP_INIT2RTR_QP, }, [MLX5_QP_STATE_RTR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTR2RTS_QP, }, [MLX5_QP_STATE_RTS] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTS2RTS_QP, }, [MLX5_QP_STATE_SQD] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, }, [MLX5_QP_STATE_SQER] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, [MLX5_QP_STATE_RTS] = MLX5_CMD_OP_SQERR2RTS_QP, }, [MLX5_QP_STATE_ERR] = { [MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP, [MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP, } }; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_qp_base *base = &qp->trans_qp.base; struct mlx5_ib_cq *send_cq, *recv_cq; struct mlx5_qp_context *context; struct mlx5_ib_pd *pd; struct mlx5_ib_port *mibport = NULL; enum mlx5_qp_state mlx5_cur, mlx5_new; enum mlx5_qp_optpar optpar; int mlx5_st; int err; u16 op; u8 tx_affinity = 0; mlx5_st = to_mlx5_st(ibqp->qp_type == IB_QPT_DRIVER ? qp->qp_sub_type : ibqp->qp_type); if (mlx5_st < 0) return -EINVAL; context = kzalloc(sizeof(*context), GFP_KERNEL); if (!context) return -ENOMEM; context->flags = cpu_to_be32(mlx5_st << 16); if (!(attr_mask & IB_QP_PATH_MIG_STATE)) { context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); } else { switch (attr->path_mig_state) { case IB_MIG_MIGRATED: context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11); break; case IB_MIG_REARM: context->flags |= cpu_to_be32(MLX5_QP_PM_REARM << 11); break; case IB_MIG_ARMED: context->flags |= cpu_to_be32(MLX5_QP_PM_ARMED << 11); break; } } if ((cur_state == IB_QPS_RESET) && (new_state == IB_QPS_INIT)) { if ((ibqp->qp_type == IB_QPT_RC) || (ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_SQPN_QP1)) || (ibqp->qp_type == IB_QPT_UC) || (ibqp->qp_type == IB_QPT_RAW_PACKET) || (ibqp->qp_type == IB_QPT_XRC_INI) || (ibqp->qp_type == IB_QPT_XRC_TGT)) { if (mlx5_lag_is_active(dev->mdev)) { u8 p = mlx5_core_native_port_num(dev->mdev); tx_affinity = (unsigned int)atomic_add_return(1, &dev->roce[p].next_port) % MLX5_MAX_PORTS + 1; context->flags |= cpu_to_be32(tx_affinity << 24); } } } if (is_sqp(ibqp->qp_type)) { context->mtu_msgmax = (IB_MTU_256 << 5) | 8; } else if ((ibqp->qp_type == IB_QPT_UD && !(qp->flags & MLX5_IB_QP_UNDERLAY)) || ibqp->qp_type == MLX5_IB_QPT_REG_UMR) { context->mtu_msgmax = (IB_MTU_4096 << 5) | 12; } else if (attr_mask & IB_QP_PATH_MTU) { if (attr->path_mtu < IB_MTU_256 || attr->path_mtu > IB_MTU_4096) { mlx5_ib_warn(dev, "invalid mtu %d\n", attr->path_mtu); err = -EINVAL; goto out; } context->mtu_msgmax = (attr->path_mtu << 5) | (u8)MLX5_CAP_GEN(dev->mdev, log_max_msg); } if (attr_mask & IB_QP_DEST_QPN) context->log_pg_sz_remote_qpn = cpu_to_be32(attr->dest_qp_num); if (attr_mask & IB_QP_PKEY_INDEX) context->pri_path.pkey_index = cpu_to_be16(attr->pkey_index); /* todo implement counter_index functionality */ if (is_sqp(ibqp->qp_type)) context->pri_path.port = qp->port; if (attr_mask & IB_QP_PORT) context->pri_path.port = attr->port_num; if (attr_mask & IB_QP_AV) { err = mlx5_set_path(dev, qp, &attr->ah_attr, &context->pri_path, attr_mask & IB_QP_PORT ? attr->port_num : qp->port, attr_mask, 0, attr, false); if (err) goto out; } if (attr_mask & IB_QP_TIMEOUT) context->pri_path.ackto_lt |= attr->timeout << 3; if (attr_mask & IB_QP_ALT_PATH) { err = mlx5_set_path(dev, qp, &attr->alt_ah_attr, &context->alt_path, attr->alt_port_num, attr_mask | IB_QP_PKEY_INDEX | IB_QP_TIMEOUT, 0, attr, true); if (err) goto out; } pd = get_pd(qp); get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq, &send_cq, &recv_cq); context->flags_pd = cpu_to_be32(pd ? pd->pdn : to_mpd(dev->devr.p0)->pdn); context->cqn_send = send_cq ? cpu_to_be32(send_cq->mcq.cqn) : 0; context->cqn_recv = recv_cq ? cpu_to_be32(recv_cq->mcq.cqn) : 0; context->params1 = cpu_to_be32(MLX5_IB_ACK_REQ_FREQ << 28); if (attr_mask & IB_QP_RNR_RETRY) context->params1 |= cpu_to_be32(attr->rnr_retry << 13); if (attr_mask & IB_QP_RETRY_CNT) context->params1 |= cpu_to_be32(attr->retry_cnt << 16); if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) { if (attr->max_rd_atomic) context->params1 |= cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21); } if (attr_mask & IB_QP_SQ_PSN) context->next_send_psn = cpu_to_be32(attr->sq_psn); if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) { if (attr->max_dest_rd_atomic) context->params2 |= cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21); } if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC)) context->params2 |= to_mlx5_access_flags(qp, attr, attr_mask); if (attr_mask & IB_QP_MIN_RNR_TIMER) context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24); if (attr_mask & IB_QP_RQ_PSN) context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn); if (attr_mask & IB_QP_QKEY) context->qkey = cpu_to_be32(attr->qkey); if (qp->rq.wqe_cnt && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->db_rec_addr = cpu_to_be64(qp->db.dma); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { u8 port_num = (attr_mask & IB_QP_PORT ? attr->port_num : qp->port) - 1; /* Underlay port should be used - index 0 function per port */ if (qp->flags & MLX5_IB_QP_UNDERLAY) port_num = 0; mibport = &dev->port[port_num]; context->qp_counter_set_usr_page |= cpu_to_be32((u32)(mibport->cnts.set_id) << 24); } if (!ibqp->uobject && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) context->sq_crq_size |= cpu_to_be16(1 << 4); if (qp->flags & MLX5_IB_QP_SQPN_QP1) context->deth_sqpn = cpu_to_be32(1); mlx5_cur = to_mlx5_state(cur_state); mlx5_new = to_mlx5_state(new_state); if (mlx5_cur >= MLX5_QP_NUM_STATE || mlx5_new >= MLX5_QP_NUM_STATE || !optab[mlx5_cur][mlx5_new]) { err = -EINVAL; goto out; } op = optab[mlx5_cur][mlx5_new]; optpar = ib_mask_to_mlx5_opt(attr_mask); optpar &= opt_mask[mlx5_cur][mlx5_new][mlx5_st]; if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { struct mlx5_modify_raw_qp_param raw_qp_param = {}; raw_qp_param.operation = op; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { raw_qp_param.rq_q_ctr_id = mibport->cnts.set_id; raw_qp_param.set_mask |= MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID; } if (attr_mask & IB_QP_RATE_LIMIT) { raw_qp_param.rl.rate = attr->rate_limit; if (ucmd->burst_info.max_burst_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_burst_bound)) { raw_qp_param.rl.max_burst_sz = ucmd->burst_info.max_burst_sz; } else { err = -EINVAL; goto out; } } if (ucmd->burst_info.typical_pkt_sz) { if (attr->rate_limit && MLX5_CAP_QOS(dev->mdev, packet_pacing_typical_size)) { raw_qp_param.rl.typical_pkt_sz = ucmd->burst_info.typical_pkt_sz; } else { err = -EINVAL; goto out; } } raw_qp_param.set_mask |= MLX5_RAW_QP_RATE_LIMIT; } err = modify_raw_packet_qp(dev, qp, &raw_qp_param, tx_affinity); } else { err = mlx5_core_qp_modify(dev->mdev, op, optpar, context, &base->mqp); } if (err) goto out; qp->state = new_state; if (attr_mask & IB_QP_ACCESS_FLAGS) qp->trans_qp.atomic_rd_en = attr->qp_access_flags; if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) qp->trans_qp.resp_depth = attr->max_dest_rd_atomic; if (attr_mask & IB_QP_PORT) qp->port = attr->port_num; if (attr_mask & IB_QP_ALT_PATH) qp->trans_qp.alt_port = attr->alt_port_num; /* * If we moved a kernel QP to RESET, clean up all old CQ * entries and reinitialize the QP. */ if (new_state == IB_QPS_RESET && !ibqp->uobject && ibqp->qp_type != IB_QPT_XRC_TGT) { mlx5_ib_cq_clean(recv_cq, base->mqp.qpn, ibqp->srq ? to_msrq(ibqp->srq) : NULL); if (send_cq != recv_cq) mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL); qp->rq.head = 0; qp->rq.tail = 0; qp->sq.head = 0; qp->sq.tail = 0; qp->sq.cur_post = 0; qp->sq.last_poll = 0; qp->db.db[MLX5_RCV_DBR] = 0; qp->db.db[MLX5_SND_DBR] = 0; } out: kfree(context); return err; } static inline bool is_valid_mask(int mask, int req, int opt) { if ((mask & req) != req) return false; if (mask & ~(req | opt)) return false; return true; } /* check valid transition for driver QP types * for now the only QP type that this function supports is DCI */ static bool modify_dci_qp_is_ok(enum ib_qp_state cur_state, enum ib_qp_state new_state, enum ib_qp_attr_mask attr_mask) { int req = IB_QP_STATE; int opt = 0; if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { req |= IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_INIT) { opt = IB_QP_PKEY_INDEX | IB_QP_PORT; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { req |= IB_QP_PATH_MTU; opt = IB_QP_PKEY_INDEX; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTR && new_state == IB_QPS_RTS) { req |= IB_QP_TIMEOUT | IB_QP_RETRY_CNT | IB_QP_RNR_RETRY | IB_QP_MAX_QP_RD_ATOMIC | IB_QP_SQ_PSN; opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state == IB_QPS_RTS && new_state == IB_QPS_RTS) { opt = IB_QP_MIN_RNR_TIMER; return is_valid_mask(attr_mask, req, opt); } else if (cur_state != IB_QPS_RESET && new_state == IB_QPS_ERR) { return is_valid_mask(attr_mask, req, opt); } return false; } /* mlx5_ib_modify_dct: modify a DCT QP * valid transitions are: * RESET to INIT: must set access_flags, pkey_index and port * INIT to RTR : must set min_rnr_timer, tclass, flow_label, * mtu, gid_index and hop_limit * Other transitions and attributes are illegal */ static int mlx5_ib_modify_dct(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_dev *dev = to_mdev(ibqp->device); enum ib_qp_state cur_state, new_state; int err = 0; int required = IB_QP_STATE; void *dctc; if (!(attr_mask & IB_QP_STATE)) return -EINVAL; cur_state = qp->state; new_state = attr->qp_state; dctc = MLX5_ADDR_OF(create_dct_in, qp->dct.in, dct_context_entry); if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) { required |= IB_QP_ACCESS_FLAGS | IB_QP_PKEY_INDEX | IB_QP_PORT; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; if (attr->port_num == 0 || attr->port_num > MLX5_CAP_GEN(dev->mdev, num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); return -EINVAL; } if (attr->qp_access_flags & IB_ACCESS_REMOTE_READ) MLX5_SET(dctc, dctc, rre, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_WRITE) MLX5_SET(dctc, dctc, rwe, 1); if (attr->qp_access_flags & IB_ACCESS_REMOTE_ATOMIC) { if (!mlx5_ib_dc_atomic_is_supported(dev)) return -EOPNOTSUPP; MLX5_SET(dctc, dctc, rae, 1); MLX5_SET(dctc, dctc, atomic_mode, MLX5_ATOMIC_MODE_DCT_CX); } MLX5_SET(dctc, dctc, pkey_index, attr->pkey_index); MLX5_SET(dctc, dctc, port, attr->port_num); MLX5_SET(dctc, dctc, counter_set_id, dev->port[attr->port_num - 1].cnts.set_id); } else if (cur_state == IB_QPS_INIT && new_state == IB_QPS_RTR) { struct mlx5_ib_modify_qp_resp resp = {}; u32 min_resp_len = offsetof(typeof(resp), dctn) + sizeof(resp.dctn); if (udata->outlen < min_resp_len) return -EINVAL; resp.response_length = min_resp_len; required |= IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU; if (!is_valid_mask(attr_mask, required, 0)) return -EINVAL; MLX5_SET(dctc, dctc, min_rnr_nak, attr->min_rnr_timer); MLX5_SET(dctc, dctc, tclass, attr->ah_attr.grh.traffic_class); MLX5_SET(dctc, dctc, flow_label, attr->ah_attr.grh.flow_label); MLX5_SET(dctc, dctc, mtu, attr->path_mtu); MLX5_SET(dctc, dctc, my_addr_index, attr->ah_attr.grh.sgid_index); MLX5_SET(dctc, dctc, hop_limit, attr->ah_attr.grh.hop_limit); err = mlx5_core_create_dct(dev->mdev, &qp->dct.mdct, qp->dct.in, MLX5_ST_SZ_BYTES(create_dct_in)); if (err) return err; resp.dctn = qp->dct.mdct.mqp.qpn; err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) { mlx5_core_destroy_dct(dev->mdev, &qp->dct.mdct); return err; } } else { mlx5_ib_warn(dev, "Modify DCT: Invalid transition from %d to %d\n", cur_state, new_state); return -EINVAL; } if (err) qp->state = IB_QPS_ERR; else qp->state = new_state; return err; } int mlx5_ib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_ib_modify_qp ucmd = {}; enum ib_qp_type qp_type; enum ib_qp_state cur_state, new_state; size_t required_cmd_sz; int err = -EINVAL; int port; enum rdma_link_layer ll = IB_LINK_LAYER_UNSPECIFIED; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (udata && udata->inlen) { required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(udata->inlen, sizeof(ucmd)))) return -EFAULT; if (ucmd.comp_mask || memchr_inv(&ucmd.reserved, 0, sizeof(ucmd.reserved)) || memchr_inv(&ucmd.burst_info.reserved, 0, sizeof(ucmd.burst_info.reserved))) return -EOPNOTSUPP; } if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_modify_qp(ibqp, attr, attr_mask); if (ibqp->qp_type == IB_QPT_DRIVER) qp_type = qp->qp_sub_type; else qp_type = (unlikely(ibqp->qp_type == MLX5_IB_QPT_HW_GSI)) ? IB_QPT_GSI : ibqp->qp_type; if (qp_type == MLX5_IB_QPT_DCT) return mlx5_ib_modify_dct(ibqp, attr, attr_mask, udata); mutex_lock(&qp->mutex); cur_state = attr_mask & IB_QP_CUR_STATE ? attr->cur_qp_state : qp->state; new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state; if (!(cur_state == new_state && cur_state == IB_QPS_RESET)) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; ll = dev->ib_dev.get_link_layer(&dev->ib_dev, port); } if (qp->flags & MLX5_IB_QP_UNDERLAY) { if (attr_mask & ~(IB_QP_STATE | IB_QP_CUR_STATE)) { mlx5_ib_dbg(dev, "invalid attr_mask 0x%x when underlay QP is used\n", attr_mask); goto out; } } else if (qp_type != MLX5_IB_QPT_REG_UMR && qp_type != MLX5_IB_QPT_DCI && !ib_modify_qp_is_ok(cur_state, new_state, qp_type, attr_mask, ll)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, ibqp->qp_type, attr_mask); goto out; } else if (qp_type == MLX5_IB_QPT_DCI && !modify_dci_qp_is_ok(cur_state, new_state, attr_mask)) { mlx5_ib_dbg(dev, "invalid QP state transition from %d to %d, qp_type %d, attr_mask 0x%x\n", cur_state, new_state, qp_type, attr_mask); goto out; } if ((attr_mask & IB_QP_PORT) && (attr->port_num == 0 || attr->port_num > dev->num_ports)) { mlx5_ib_dbg(dev, "invalid port number %d. number of ports is %d\n", attr->port_num, dev->num_ports); goto out; } if (attr_mask & IB_QP_PKEY_INDEX) { port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port; if (attr->pkey_index >= dev->mdev->port_caps[port - 1].pkey_table_len) { mlx5_ib_dbg(dev, "invalid pkey index %d\n", attr->pkey_index); goto out; } } if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC && attr->max_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_res_qp))) { mlx5_ib_dbg(dev, "invalid max_rd_atomic value %d\n", attr->max_rd_atomic); goto out; } if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC && attr->max_dest_rd_atomic > (1 << MLX5_CAP_GEN(dev->mdev, log_max_ra_req_qp))) { mlx5_ib_dbg(dev, "invalid max_dest_rd_atomic value %d\n", attr->max_dest_rd_atomic); goto out; } if (cur_state == new_state && cur_state == IB_QPS_RESET) { err = 0; goto out; } err = __mlx5_ib_modify_qp(ibqp, attr, attr_mask, cur_state, new_state, &ucmd); out: mutex_unlock(&qp->mutex); return err; } static int mlx5_wq_overflow(struct mlx5_ib_wq *wq, int nreq, struct ib_cq *ib_cq) { struct mlx5_ib_cq *cq; unsigned cur; cur = wq->head - wq->tail; if (likely(cur + nreq < wq->max_post)) return 0; cq = to_mcq(ib_cq); spin_lock(&cq->lock); cur = wq->head - wq->tail; spin_unlock(&cq->lock); return cur + nreq >= wq->max_post; } static __always_inline void set_raddr_seg(struct mlx5_wqe_raddr_seg *rseg, u64 remote_addr, u32 rkey) { rseg->raddr = cpu_to_be64(remote_addr); rseg->rkey = cpu_to_be32(rkey); rseg->reserved = 0; } static void *set_eth_seg(struct mlx5_wqe_eth_seg *eseg, const struct ib_send_wr *wr, void *qend, struct mlx5_ib_qp *qp, int *size) { void *seg = eseg; memset(eseg, 0, sizeof(struct mlx5_wqe_eth_seg)); if (wr->send_flags & IB_SEND_IP_CSUM) eseg->cs_flags = MLX5_ETH_WQE_L3_CSUM | MLX5_ETH_WQE_L4_CSUM; seg += sizeof(struct mlx5_wqe_eth_seg); *size += sizeof(struct mlx5_wqe_eth_seg) / 16; if (wr->opcode == IB_WR_LSO) { struct ib_ud_wr *ud_wr = container_of(wr, struct ib_ud_wr, wr); int size_of_inl_hdr_start = sizeof(eseg->inline_hdr.start); u64 left, leftlen, copysz; void *pdata = ud_wr->header; left = ud_wr->hlen; eseg->mss = cpu_to_be16(ud_wr->mss); eseg->inline_hdr.sz = cpu_to_be16(left); /* * check if there is space till the end of queue, if yes, * copy all in one shot, otherwise copy till the end of queue, * rollback and than the copy the left */ leftlen = qend - (void *)eseg->inline_hdr.start; copysz = min_t(u64, leftlen, left); memcpy(seg - size_of_inl_hdr_start, pdata, copysz); if (likely(copysz > size_of_inl_hdr_start)) { seg += ALIGN(copysz - size_of_inl_hdr_start, 16); *size += ALIGN(copysz - size_of_inl_hdr_start, 16) / 16; } if (unlikely(copysz < left)) { /* the last wqe in the queue */ seg = mlx5_get_send_wqe(qp, 0); left -= copysz; pdata += copysz; memcpy(seg, pdata, left); seg += ALIGN(left, 16); *size += ALIGN(left, 16) / 16; } } return seg; } static void set_datagram_seg(struct mlx5_wqe_datagram_seg *dseg, const struct ib_send_wr *wr) { memcpy(&dseg->av, &to_mah(ud_wr(wr)->ah)->av, sizeof(struct mlx5_av)); dseg->av.dqp_dct = cpu_to_be32(ud_wr(wr)->remote_qpn | MLX5_EXTENDED_UD_AV); dseg->av.key.qkey.qkey = cpu_to_be32(ud_wr(wr)->remote_qkey); } static void set_data_ptr_seg(struct mlx5_wqe_data_seg *dseg, struct ib_sge *sg) { dseg->byte_count = cpu_to_be32(sg->length); dseg->lkey = cpu_to_be32(sg->lkey); dseg->addr = cpu_to_be64(sg->addr); } static u64 get_xlt_octo(u64 bytes) { return ALIGN(bytes, MLX5_IB_UMR_XLT_ALIGNMENT) / MLX5_IB_UMR_OCTOWORD; } static __be64 frwr_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_A | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 sig_mkey_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR | MLX5_MKEY_MASK_EN_SIGERR | MLX5_MKEY_MASK_EN_RINVAL | MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW | MLX5_MKEY_MASK_SMALL_FENCE | MLX5_MKEY_MASK_FREE | MLX5_MKEY_MASK_BSF_EN; return cpu_to_be64(result); } static void set_reg_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr, struct mlx5_ib_mr *mr, bool umr_inline) { int size = mr->ndescs * mr->desc_size; memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_UMR_CHECK_NOT_FREE; if (umr_inline) umr->flags |= MLX5_UMR_INLINE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->mkey_mask = frwr_mkey_mask(); } static void set_linv_umr_seg(struct mlx5_wqe_umr_ctrl_seg *umr) { memset(umr, 0, sizeof(*umr)); umr->mkey_mask = cpu_to_be64(MLX5_MKEY_MASK_FREE); umr->flags = MLX5_UMR_INLINE; } static __be64 get_umr_enable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_KEY | MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_disable_mr_mask(void) { u64 result; result = MLX5_MKEY_MASK_FREE; return cpu_to_be64(result); } static __be64 get_umr_update_translation_mask(void) { u64 result; result = MLX5_MKEY_MASK_LEN | MLX5_MKEY_MASK_PAGE_SIZE | MLX5_MKEY_MASK_START_ADDR; return cpu_to_be64(result); } static __be64 get_umr_update_access_mask(int atomic) { u64 result; result = MLX5_MKEY_MASK_LR | MLX5_MKEY_MASK_LW | MLX5_MKEY_MASK_RR | MLX5_MKEY_MASK_RW; if (atomic) result |= MLX5_MKEY_MASK_A; return cpu_to_be64(result); } static __be64 get_umr_update_pd_mask(void) { u64 result; result = MLX5_MKEY_MASK_PD; return cpu_to_be64(result); } static int umr_check_mkey_mask(struct mlx5_ib_dev *dev, u64 mask) { if ((mask & MLX5_MKEY_MASK_PAGE_SIZE && MLX5_CAP_GEN(dev->mdev, umr_modify_entity_size_disabled)) || (mask & MLX5_MKEY_MASK_A && MLX5_CAP_GEN(dev->mdev, umr_modify_atomic_disabled))) return -EPERM; return 0; } static int set_reg_umr_segment(struct mlx5_ib_dev *dev, struct mlx5_wqe_umr_ctrl_seg *umr, const struct ib_send_wr *wr, int atomic) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(umr, 0, sizeof(*umr)); if (wr->send_flags & MLX5_IB_SEND_UMR_FAIL_IF_FREE) umr->flags = MLX5_UMR_CHECK_FREE; /* fail if free */ else umr->flags = MLX5_UMR_CHECK_NOT_FREE; /* fail if not free */ umr->xlt_octowords = cpu_to_be16(get_xlt_octo(umrwr->xlt_size)); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_XLT) { u64 offset = get_xlt_octo(umrwr->offset); umr->xlt_offset = cpu_to_be16(offset & 0xffff); umr->xlt_offset_47_16 = cpu_to_be32(offset >> 16); umr->flags |= MLX5_UMR_TRANSLATION_OFFSET_EN; } if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION) umr->mkey_mask |= get_umr_update_translation_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS) { umr->mkey_mask |= get_umr_update_access_mask(atomic); umr->mkey_mask |= get_umr_update_pd_mask(); } if (wr->send_flags & MLX5_IB_SEND_UMR_ENABLE_MR) umr->mkey_mask |= get_umr_enable_mr_mask(); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) umr->mkey_mask |= get_umr_disable_mr_mask(); if (!wr->num_sge) umr->flags |= MLX5_UMR_INLINE; return umr_check_mkey_mask(dev, be64_to_cpu(umr->mkey_mask)); } static u8 get_umr_flags(int acc) { return (acc & IB_ACCESS_REMOTE_ATOMIC ? MLX5_PERM_ATOMIC : 0) | (acc & IB_ACCESS_REMOTE_WRITE ? MLX5_PERM_REMOTE_WRITE : 0) | (acc & IB_ACCESS_REMOTE_READ ? MLX5_PERM_REMOTE_READ : 0) | (acc & IB_ACCESS_LOCAL_WRITE ? MLX5_PERM_LOCAL_WRITE : 0) | MLX5_PERM_LOCAL_READ | MLX5_PERM_UMR_EN; } static void set_reg_mkey_seg(struct mlx5_mkey_seg *seg, struct mlx5_ib_mr *mr, u32 key, int access) { int ndescs = ALIGN(mr->ndescs, 8) >> 1; memset(seg, 0, sizeof(*seg)); if (mr->access_mode == MLX5_MKC_ACCESS_MODE_MTT) seg->log2_page_size = ilog2(mr->ibmr.page_size); else if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS) /* KLMs take twice the size of MTTs */ ndescs *= 2; seg->flags = get_umr_flags(access) | mr->access_mode; seg->qpn_mkey7_0 = cpu_to_be32((key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL); seg->start_addr = cpu_to_be64(mr->ibmr.iova); seg->len = cpu_to_be64(mr->ibmr.length); seg->xlt_oct_size = cpu_to_be32(ndescs); } static void set_linv_mkey_seg(struct mlx5_mkey_seg *seg) { memset(seg, 0, sizeof(*seg)); seg->status = MLX5_MKEY_STATUS_FREE; } static void set_reg_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_send_wr *wr) { const struct mlx5_umr_wr *umrwr = umr_wr(wr); memset(seg, 0, sizeof(*seg)); if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR) seg->status = MLX5_MKEY_STATUS_FREE; seg->flags = convert_access(umrwr->access_flags); if (umrwr->pd) seg->flags_pd = cpu_to_be32(to_mpd(umrwr->pd)->pdn); if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION && !umrwr->length) seg->flags_pd |= cpu_to_be32(MLX5_MKEY_LEN64); seg->start_addr = cpu_to_be64(umrwr->virt_addr); seg->len = cpu_to_be64(umrwr->length); seg->log2_page_size = umrwr->page_shift; seg->qpn_mkey7_0 = cpu_to_be32(0xffffff00 | mlx5_mkey_variant(umrwr->mkey)); } static void set_reg_data_seg(struct mlx5_wqe_data_seg *dseg, struct mlx5_ib_mr *mr, struct mlx5_ib_pd *pd) { int bcount = mr->desc_size * mr->ndescs; dseg->addr = cpu_to_be64(mr->desc_map); dseg->byte_count = cpu_to_be32(ALIGN(bcount, 64)); dseg->lkey = cpu_to_be32(pd->ibpd.local_dma_lkey); } static void set_reg_umr_inline_seg(void *seg, struct mlx5_ib_qp *qp, struct mlx5_ib_mr *mr, int mr_list_size) { void *qend = qp->sq.qend; void *addr = mr->descs; int copy; if (unlikely(seg + mr_list_size > qend)) { copy = qend - seg; memcpy(seg, addr, copy); addr += copy; mr_list_size -= copy; seg = mlx5_get_send_wqe(qp, 0); } memcpy(seg, addr, mr_list_size); seg += mr_list_size; } static __be32 send_ieth(const struct ib_send_wr *wr) { switch (wr->opcode) { case IB_WR_SEND_WITH_IMM: case IB_WR_RDMA_WRITE_WITH_IMM: return wr->ex.imm_data; case IB_WR_SEND_WITH_INV: return cpu_to_be32(wr->ex.invalidate_rkey); default: return 0; } } static u8 calc_sig(void *wqe, int size) { u8 *p = wqe; u8 res = 0; int i; for (i = 0; i < size; i++) res ^= p[i]; return ~res; } static u8 wq_sig(void *wqe) { return calc_sig(wqe, (*((u8 *)wqe + 8) & 0x3f) << 4); } static int set_data_inl_seg(struct mlx5_ib_qp *qp, const struct ib_send_wr *wr, void *wqe, int *sz) { struct mlx5_wqe_inline_seg *seg; void *qend = qp->sq.qend; void *addr; int inl = 0; int copy; int len; int i; seg = wqe; wqe += sizeof(*seg); for (i = 0; i < wr->num_sge; i++) { addr = (void *)(unsigned long)(wr->sg_list[i].addr); len = wr->sg_list[i].length; inl += len; if (unlikely(inl > qp->max_inline_data)) return -ENOMEM; if (unlikely(wqe + len > qend)) { copy = qend - wqe; memcpy(wqe, addr, copy); addr += copy; len -= copy; wqe = mlx5_get_send_wqe(qp, 0); } memcpy(wqe, addr, len); wqe += len; } seg->byte_count = cpu_to_be32(inl | MLX5_INLINE_SEG); *sz = ALIGN(inl + sizeof(seg->byte_count), 16) / 16; return 0; } static u16 prot_field_size(enum ib_signature_type type) { switch (type) { case IB_SIG_TYPE_T10_DIF: return MLX5_DIF_SIZE; default: return 0; } } static u8 bs_selector(int block_size) { switch (block_size) { case 512: return 0x1; case 520: return 0x2; case 4096: return 0x3; case 4160: return 0x4; case 1073741824: return 0x5; default: return 0; } } static void mlx5_fill_inl_bsf(struct ib_sig_domain *domain, struct mlx5_bsf_inl *inl) { /* Valid inline section and allow BSF refresh */ inl->vld_refresh = cpu_to_be16(MLX5_BSF_INL_VALID | MLX5_BSF_REFRESH_DIF); inl->dif_apptag = cpu_to_be16(domain->sig.dif.app_tag); inl->dif_reftag = cpu_to_be32(domain->sig.dif.ref_tag); /* repeating block */ inl->rp_inv_seed = MLX5_BSF_REPEAT_BLOCK; inl->sig_type = domain->sig.dif.bg_type == IB_T10DIF_CRC ? MLX5_DIF_CRC : MLX5_DIF_IPCS; if (domain->sig.dif.ref_remap) inl->dif_inc_ref_guard_check |= MLX5_BSF_INC_REFTAG; if (domain->sig.dif.app_escape) { if (domain->sig.dif.ref_escape) inl->dif_inc_ref_guard_check |= MLX5_BSF_APPREF_ESCAPE; else inl->dif_inc_ref_guard_check |= MLX5_BSF_APPTAG_ESCAPE; } inl->dif_app_bitmask_check = cpu_to_be16(domain->sig.dif.apptag_check_mask); } static int mlx5_set_bsf(struct ib_mr *sig_mr, struct ib_sig_attrs *sig_attrs, struct mlx5_bsf *bsf, u32 data_size) { struct mlx5_core_sig_ctx *msig = to_mmr(sig_mr)->sig; struct mlx5_bsf_basic *basic = &bsf->basic; struct ib_sig_domain *mem = &sig_attrs->mem; struct ib_sig_domain *wire = &sig_attrs->wire; memset(bsf, 0, sizeof(*bsf)); /* Basic + Extended + Inline */ basic->bsf_size_sbs = 1 << 7; /* Input domain check byte mask */ basic->check_byte_mask = sig_attrs->check_mask; basic->raw_data_size = cpu_to_be32(data_size); /* Memory domain */ switch (sig_attrs->mem.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: basic->mem.bs_selector = bs_selector(mem->sig.dif.pi_interval); basic->m_bfs_psv = cpu_to_be32(msig->psv_memory.psv_idx); mlx5_fill_inl_bsf(mem, &bsf->m_inl); break; default: return -EINVAL; } /* Wire domain */ switch (sig_attrs->wire.sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: if (mem->sig.dif.pi_interval == wire->sig.dif.pi_interval && mem->sig_type == wire->sig_type) { /* Same block structure */ basic->bsf_size_sbs |= 1 << 4; if (mem->sig.dif.bg_type == wire->sig.dif.bg_type) basic->wire.copy_byte_mask |= MLX5_CPY_GRD_MASK; if (mem->sig.dif.app_tag == wire->sig.dif.app_tag) basic->wire.copy_byte_mask |= MLX5_CPY_APP_MASK; if (mem->sig.dif.ref_tag == wire->sig.dif.ref_tag) basic->wire.copy_byte_mask |= MLX5_CPY_REF_MASK; } else basic->wire.bs_selector = bs_selector(wire->sig.dif.pi_interval); basic->w_bfs_psv = cpu_to_be32(msig->psv_wire.psv_idx); mlx5_fill_inl_bsf(wire, &bsf->w_inl); break; default: return -EINVAL; } return 0; } static int set_sig_data_segment(const struct ib_sig_handover_wr *wr, struct mlx5_ib_qp *qp, void **seg, int *size) { struct ib_sig_attrs *sig_attrs = wr->sig_attrs; struct ib_mr *sig_mr = wr->sig_mr; struct mlx5_bsf *bsf; u32 data_len = wr->wr.sg_list->length; u32 data_key = wr->wr.sg_list->lkey; u64 data_va = wr->wr.sg_list->addr; int ret; int wqe_size; if (!wr->prot || (data_key == wr->prot->lkey && data_va == wr->prot->addr && data_len == wr->prot->length)) { /** * Source domain doesn't contain signature information * or data and protection are interleaved in memory. * So need construct: * ------------------ * | data_klm | * ------------------ * | BSF | * ------------------ **/ struct mlx5_klm *data_klm = *seg; data_klm->bcount = cpu_to_be32(data_len); data_klm->key = cpu_to_be32(data_key); data_klm->va = cpu_to_be64(data_va); wqe_size = ALIGN(sizeof(*data_klm), 64); } else { /** * Source domain contains signature information * So need construct a strided block format: * --------------------------- * | stride_block_ctrl | * --------------------------- * | data_klm | * --------------------------- * | prot_klm | * --------------------------- * | BSF | * --------------------------- **/ struct mlx5_stride_block_ctrl_seg *sblock_ctrl; struct mlx5_stride_block_entry *data_sentry; struct mlx5_stride_block_entry *prot_sentry; u32 prot_key = wr->prot->lkey; u64 prot_va = wr->prot->addr; u16 block_size = sig_attrs->mem.sig.dif.pi_interval; int prot_size; sblock_ctrl = *seg; data_sentry = (void *)sblock_ctrl + sizeof(*sblock_ctrl); prot_sentry = (void *)data_sentry + sizeof(*data_sentry); prot_size = prot_field_size(sig_attrs->mem.sig_type); if (!prot_size) { pr_err("Bad block size given: %u\n", block_size); return -EINVAL; } sblock_ctrl->bcount_per_cycle = cpu_to_be32(block_size + prot_size); sblock_ctrl->op = cpu_to_be32(MLX5_STRIDE_BLOCK_OP); sblock_ctrl->repeat_count = cpu_to_be32(data_len / block_size); sblock_ctrl->num_entries = cpu_to_be16(2); data_sentry->bcount = cpu_to_be16(block_size); data_sentry->key = cpu_to_be32(data_key); data_sentry->va = cpu_to_be64(data_va); data_sentry->stride = cpu_to_be16(block_size); prot_sentry->bcount = cpu_to_be16(prot_size); prot_sentry->key = cpu_to_be32(prot_key); prot_sentry->va = cpu_to_be64(prot_va); prot_sentry->stride = cpu_to_be16(prot_size); wqe_size = ALIGN(sizeof(*sblock_ctrl) + sizeof(*data_sentry) + sizeof(*prot_sentry), 64); } *seg += wqe_size; *size += wqe_size / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); bsf = *seg; ret = mlx5_set_bsf(sig_mr, sig_attrs, bsf, data_len); if (ret) return -EINVAL; *seg += sizeof(*bsf); *size += sizeof(*bsf) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); return 0; } static void set_sig_mkey_segment(struct mlx5_mkey_seg *seg, const struct ib_sig_handover_wr *wr, u32 size, u32 length, u32 pdn) { struct ib_mr *sig_mr = wr->sig_mr; u32 sig_key = sig_mr->rkey; u8 sigerr = to_mmr(sig_mr)->sig->sigerr_count & 1; memset(seg, 0, sizeof(*seg)); seg->flags = get_umr_flags(wr->access_flags) | MLX5_MKC_ACCESS_MODE_KLMS; seg->qpn_mkey7_0 = cpu_to_be32((sig_key & 0xff) | 0xffffff00); seg->flags_pd = cpu_to_be32(MLX5_MKEY_REMOTE_INVAL | sigerr << 26 | MLX5_MKEY_BSF_EN | pdn); seg->len = cpu_to_be64(length); seg->xlt_oct_size = cpu_to_be32(get_xlt_octo(size)); seg->bsfs_octo_size = cpu_to_be32(MLX5_MKEY_BSF_OCTO_SIZE); } static void set_sig_umr_segment(struct mlx5_wqe_umr_ctrl_seg *umr, u32 size) { memset(umr, 0, sizeof(*umr)); umr->flags = MLX5_FLAGS_INLINE | MLX5_FLAGS_CHECK_FREE; umr->xlt_octowords = cpu_to_be16(get_xlt_octo(size)); umr->bsf_octowords = cpu_to_be16(MLX5_MKEY_BSF_OCTO_SIZE); umr->mkey_mask = sig_mkey_mask(); } static int set_sig_umr_wr(const struct ib_send_wr *send_wr, struct mlx5_ib_qp *qp, void **seg, int *size) { const struct ib_sig_handover_wr *wr = sig_handover_wr(send_wr); struct mlx5_ib_mr *sig_mr = to_mmr(wr->sig_mr); u32 pdn = get_pd(qp)->pdn; u32 xlt_size; int region_len, ret; if (unlikely(wr->wr.num_sge != 1) || unlikely(wr->access_flags & IB_ACCESS_REMOTE_ATOMIC) || unlikely(!sig_mr->sig) || unlikely(!qp->signature_en) || unlikely(!sig_mr->sig->sig_status_checked)) return -EINVAL; /* length of the protected region, data + protection */ region_len = wr->wr.sg_list->length; if (wr->prot && (wr->prot->lkey != wr->wr.sg_list->lkey || wr->prot->addr != wr->wr.sg_list->addr || wr->prot->length != wr->wr.sg_list->length)) region_len += wr->prot->length; /** * KLM octoword size - if protection was provided * then we use strided block format (3 octowords), * else we use single KLM (1 octoword) **/ xlt_size = wr->prot ? 0x30 : sizeof(struct mlx5_klm); set_sig_umr_segment(*seg, xlt_size); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_sig_mkey_segment(*seg, wr, xlt_size, region_len, pdn); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); ret = set_sig_data_segment(wr, qp, seg, size); if (ret) return ret; sig_mr->sig->sig_status_checked = false; return 0; } static int set_psv_wr(struct ib_sig_domain *domain, u32 psv_idx, void **seg, int *size) { struct mlx5_seg_set_psv *psv_seg = *seg; memset(psv_seg, 0, sizeof(*psv_seg)); psv_seg->psv_num = cpu_to_be32(psv_idx); switch (domain->sig_type) { case IB_SIG_TYPE_NONE: break; case IB_SIG_TYPE_T10_DIF: psv_seg->transient_sig = cpu_to_be32(domain->sig.dif.bg << 16 | domain->sig.dif.app_tag); psv_seg->ref_tag = cpu_to_be32(domain->sig.dif.ref_tag); break; default: pr_err("Bad signature type (%d) is given.\n", domain->sig_type); return -EINVAL; } *seg += sizeof(*psv_seg); *size += sizeof(*psv_seg) / 16; return 0; } static int set_reg_wr(struct mlx5_ib_qp *qp, const struct ib_reg_wr *wr, void **seg, int *size) { struct mlx5_ib_mr *mr = to_mmr(wr->mr); struct mlx5_ib_pd *pd = to_mpd(qp->ibqp.pd); int mr_list_size = mr->ndescs * mr->desc_size; bool umr_inline = mr_list_size <= MLX5_IB_SQ_UMR_INLINE_THRESHOLD; if (unlikely(wr->wr.send_flags & IB_SEND_INLINE)) { mlx5_ib_warn(to_mdev(qp->ibqp.device), "Invalid IB_SEND_INLINE send flag\n"); return -EINVAL; } set_reg_umr_seg(*seg, mr, umr_inline); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_seg(*seg, mr, wr->key, wr->access); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); if (umr_inline) { set_reg_umr_inline_seg(*seg, qp, mr, mr_list_size); *size += get_xlt_octo(mr_list_size); } else { set_reg_data_seg(*seg, mr, pd); *seg += sizeof(struct mlx5_wqe_data_seg); *size += (sizeof(struct mlx5_wqe_data_seg) / 16); } return 0; } static void set_linv_wr(struct mlx5_ib_qp *qp, void **seg, int *size) { set_linv_umr_seg(*seg); *seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); *size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); set_linv_mkey_seg(*seg); *seg += sizeof(struct mlx5_mkey_seg); *size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((*seg == qp->sq.qend))) *seg = mlx5_get_send_wqe(qp, 0); } static void dump_wqe(struct mlx5_ib_qp *qp, int idx, int size_16) { __be32 *p = NULL; int tidx = idx; int i, j; pr_debug("dump wqe at %p\n", mlx5_get_send_wqe(qp, tidx)); for (i = 0, j = 0; i < size_16 * 4; i += 4, j += 4) { if ((i & 0xf) == 0) { void *buf = mlx5_get_send_wqe(qp, tidx); tidx = (tidx + 1) & (qp->sq.wqe_cnt - 1); p = buf; j = 0; } pr_debug("%08x %08x %08x %08x\n", be32_to_cpu(p[j]), be32_to_cpu(p[j + 1]), be32_to_cpu(p[j + 2]), be32_to_cpu(p[j + 3])); } } static int __begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq, bool send_signaled, bool solicited) { if (unlikely(mlx5_wq_overflow(&qp->sq, nreq, qp->ibqp.send_cq))) return -ENOMEM; *idx = qp->sq.cur_post & (qp->sq.wqe_cnt - 1); *seg = mlx5_get_send_wqe(qp, *idx); *ctrl = *seg; *(uint32_t *)(*seg + 8) = 0; (*ctrl)->imm = send_ieth(wr); (*ctrl)->fm_ce_se = qp->sq_signal_bits | (send_signaled ? MLX5_WQE_CTRL_CQ_UPDATE : 0) | (solicited ? MLX5_WQE_CTRL_SOLICITED : 0); *seg += sizeof(**ctrl); *size = sizeof(**ctrl) / 16; return 0; } static int begin_wqe(struct mlx5_ib_qp *qp, void **seg, struct mlx5_wqe_ctrl_seg **ctrl, const struct ib_send_wr *wr, unsigned *idx, int *size, int nreq) { return __begin_wqe(qp, seg, ctrl, wr, idx, size, nreq, wr->send_flags & IB_SEND_SIGNALED, wr->send_flags & IB_SEND_SOLICITED); } static void finish_wqe(struct mlx5_ib_qp *qp, struct mlx5_wqe_ctrl_seg *ctrl, u8 size, unsigned idx, u64 wr_id, int nreq, u8 fence, u32 mlx5_opcode) { u8 opmod = 0; ctrl->opmod_idx_opcode = cpu_to_be32(((u32)(qp->sq.cur_post) << 8) | mlx5_opcode | ((u32)opmod << 24)); ctrl->qpn_ds = cpu_to_be32(size | (qp->trans_qp.base.mqp.qpn << 8)); ctrl->fm_ce_se |= fence; if (unlikely(qp->wq_sig)) ctrl->signature = wq_sig(ctrl); qp->sq.wrid[idx] = wr_id; qp->sq.w_list[idx].opcode = mlx5_opcode; qp->sq.wqe_head[idx] = qp->sq.head + nreq; qp->sq.cur_post += DIV_ROUND_UP(size * 16, MLX5_SEND_WQE_BB); qp->sq.w_list[idx].next = qp->sq.cur_post; } static int _mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr, bool drain) { struct mlx5_wqe_ctrl_seg *ctrl = NULL; /* compiler warning */ struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_qp *qp; struct mlx5_ib_mr *mr; struct mlx5_wqe_data_seg *dpseg; struct mlx5_wqe_xrc_seg *xrc; struct mlx5_bf *bf; int uninitialized_var(size); void *qend; unsigned long flags; unsigned idx; int err = 0; int num_sge; void *seg; int nreq; int i; u8 next_fence = 0; u8 fence; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_send(ibqp, wr, bad_wr); qp = to_mqp(ibqp); bf = &qp->bf; qend = qp->sq.qend; spin_lock_irqsave(&qp->sq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } for (nreq = 0; wr; nreq++, wr = wr->next) { if (unlikely(wr->opcode >= ARRAY_SIZE(mlx5_ib_opcode))) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } num_sge = wr->num_sge; if (unlikely(num_sge > qp->sq.max_gs)) { mlx5_ib_warn(dev, "\n"); err = -EINVAL; *bad_wr = wr; goto out; } err = begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } if (wr->opcode == IB_WR_LOCAL_INV || wr->opcode == IB_WR_REG_MR) { fence = dev->umr_fence; next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; } else if (wr->send_flags & IB_SEND_FENCE) { if (qp->next_fence) fence = MLX5_FENCE_MODE_SMALL_AND_FENCE; else fence = MLX5_FENCE_MODE_FENCE; } else { fence = qp->next_fence; } switch (ibqp->qp_type) { case IB_QPT_XRC_INI: xrc = seg; seg += sizeof(*xrc); size += sizeof(*xrc) / 16; /* fall through */ case IB_QPT_RC: switch (wr->opcode) { case IB_WR_RDMA_READ: case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; case IB_WR_ATOMIC_CMP_AND_SWP: case IB_WR_ATOMIC_FETCH_AND_ADD: case IB_WR_MASKED_ATOMIC_CMP_AND_SWP: mlx5_ib_warn(dev, "Atomic operations are not supported yet\n"); err = -ENOSYS; *bad_wr = wr; goto out; case IB_WR_LOCAL_INV: qp->sq.wr_data[idx] = IB_WR_LOCAL_INV; ctrl->imm = cpu_to_be32(wr->ex.invalidate_rkey); set_linv_wr(qp, &seg, &size); num_sge = 0; break; case IB_WR_REG_MR: qp->sq.wr_data[idx] = IB_WR_REG_MR; ctrl->imm = cpu_to_be32(reg_wr(wr)->key); err = set_reg_wr(qp, reg_wr(wr), &seg, &size); if (err) { *bad_wr = wr; goto out; } num_sge = 0; break; case IB_WR_REG_SIG_MR: qp->sq.wr_data[idx] = IB_WR_REG_SIG_MR; mr = to_mmr(sig_handover_wr(wr)->sig_mr); ctrl->imm = cpu_to_be32(mr->ibmr.rkey); err = set_sig_umr_wr(wr, qp, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_UMR); /* * SET_PSV WQEs are not signaled and solicited * on error */ err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->mem, mr->sig->psv_memory.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); err = __begin_wqe(qp, &seg, &ctrl, wr, &idx, &size, nreq, false, true); if (err) { mlx5_ib_warn(dev, "\n"); err = -ENOMEM; *bad_wr = wr; goto out; } err = set_psv_wr(&sig_handover_wr(wr)->sig_attrs->wire, mr->sig->psv_wire.psv_idx, &seg, &size); if (err) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, MLX5_OPCODE_SET_PSV); qp->next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; num_sge = 0; goto skip_psv; default: break; } break; case IB_QPT_UC: switch (wr->opcode) { case IB_WR_RDMA_WRITE: case IB_WR_RDMA_WRITE_WITH_IMM: set_raddr_seg(seg, rdma_wr(wr)->remote_addr, rdma_wr(wr)->rkey); seg += sizeof(struct mlx5_wqe_raddr_seg); size += sizeof(struct mlx5_wqe_raddr_seg) / 16; break; default: break; } break; case IB_QPT_SMI: if (unlikely(!mdev->port_caps[qp->port - 1].has_smi)) { mlx5_ib_warn(dev, "Send SMP MADs is not allowed\n"); err = -EPERM; *bad_wr = wr; goto out; } /* fall through */ case MLX5_IB_QPT_HW_GSI: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; case IB_QPT_UD: set_datagram_seg(seg, wr); seg += sizeof(struct mlx5_wqe_datagram_seg); size += sizeof(struct mlx5_wqe_datagram_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); /* handle qp that supports ud offload */ if (qp->flags & IB_QP_CREATE_IPOIB_UD_LSO) { struct mlx5_wqe_eth_pad *pad; pad = seg; memset(pad, 0, sizeof(struct mlx5_wqe_eth_pad)); seg += sizeof(struct mlx5_wqe_eth_pad); size += sizeof(struct mlx5_wqe_eth_pad) / 16; seg = set_eth_seg(seg, wr, qend, qp, &size); if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); } break; case MLX5_IB_QPT_REG_UMR: if (wr->opcode != MLX5_IB_WR_UMR) { err = -EINVAL; mlx5_ib_warn(dev, "bad opcode\n"); goto out; } qp->sq.wr_data[idx] = MLX5_IB_WR_UMR; ctrl->imm = cpu_to_be32(umr_wr(wr)->mkey); err = set_reg_umr_segment(dev, seg, wr, !!(MLX5_CAP_GEN(mdev, atomic))); if (unlikely(err)) goto out; seg += sizeof(struct mlx5_wqe_umr_ctrl_seg); size += sizeof(struct mlx5_wqe_umr_ctrl_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); set_reg_mkey_segment(seg, wr); seg += sizeof(struct mlx5_mkey_seg); size += sizeof(struct mlx5_mkey_seg) / 16; if (unlikely((seg == qend))) seg = mlx5_get_send_wqe(qp, 0); break; default: break; } if (wr->send_flags & IB_SEND_INLINE && num_sge) { int uninitialized_var(sz); err = set_data_inl_seg(qp, wr, seg, &sz); if (unlikely(err)) { mlx5_ib_warn(dev, "\n"); *bad_wr = wr; goto out; } size += sz; } else { dpseg = seg; for (i = 0; i < num_sge; i++) { if (unlikely(dpseg == qend)) { seg = mlx5_get_send_wqe(qp, 0); dpseg = seg; } if (likely(wr->sg_list[i].length)) { set_data_ptr_seg(dpseg, wr->sg_list + i); size += sizeof(struct mlx5_wqe_data_seg) / 16; dpseg++; } } } qp->next_fence = next_fence; finish_wqe(qp, ctrl, size, idx, wr->wr_id, nreq, fence, mlx5_ib_opcode[wr->opcode]); skip_psv: if (0) dump_wqe(qp, idx, size); } out: if (likely(nreq)) { qp->sq.head += nreq; /* Make sure that descriptors are written before * updating doorbell record and ringing the doorbell */ wmb(); qp->db.db[MLX5_SND_DBR] = cpu_to_be32(qp->sq.cur_post); /* Make sure doorbell record is visible to the HCA before * we hit doorbell */ wmb(); /* currently we support only regular doorbells */ mlx5_write64((__be32 *)ctrl, bf->bfreg->map + bf->offset, NULL); /* Make sure doorbells don't leak out of SQ spinlock * and reach the HCA out of order. */ mmiowb(); bf->offset ^= bf->buf_size; } spin_unlock_irqrestore(&qp->sq.lock, flags); return err; } int mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr) { return _mlx5_ib_post_send(ibqp, wr, bad_wr, false); } static void set_sig_seg(struct mlx5_rwqe_sig *sig, int size) { sig->signature = calc_sig(sig, size); } static int _mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr, bool drain) { struct mlx5_ib_qp *qp = to_mqp(ibqp); struct mlx5_wqe_data_seg *scat; struct mlx5_rwqe_sig *sig; struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_core_dev *mdev = dev->mdev; unsigned long flags; int err = 0; int nreq; int ind; int i; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_post_recv(ibqp, wr, bad_wr); spin_lock_irqsave(&qp->rq.lock, flags); if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR && !drain) { err = -EIO; *bad_wr = wr; nreq = 0; goto out; } ind = qp->rq.head & (qp->rq.wqe_cnt - 1); for (nreq = 0; wr; nreq++, wr = wr->next) { if (mlx5_wq_overflow(&qp->rq, nreq, qp->ibqp.recv_cq)) { err = -ENOMEM; *bad_wr = wr; goto out; } if (unlikely(wr->num_sge > qp->rq.max_gs)) { err = -EINVAL; *bad_wr = wr; goto out; } scat = get_recv_wqe(qp, ind); if (qp->wq_sig) scat++; for (i = 0; i < wr->num_sge; i++) set_data_ptr_seg(scat + i, wr->sg_list + i); if (i < qp->rq.max_gs) { scat[i].byte_count = 0; scat[i].lkey = cpu_to_be32(MLX5_INVALID_LKEY); scat[i].addr = 0; } if (qp->wq_sig) { sig = (struct mlx5_rwqe_sig *)scat; set_sig_seg(sig, (qp->rq.max_gs + 1) << 2); } qp->rq.wrid[ind] = wr->wr_id; ind = (ind + 1) & (qp->rq.wqe_cnt - 1); } out: if (likely(nreq)) { qp->rq.head += nreq; /* Make sure that descriptors are written before * doorbell record. */ wmb(); *qp->db.db = cpu_to_be32(qp->rq.head & 0xffff); } spin_unlock_irqrestore(&qp->rq.lock, flags); return err; } int mlx5_ib_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr, const struct ib_recv_wr **bad_wr) { return _mlx5_ib_post_recv(ibqp, wr, bad_wr, false); } static inline enum ib_qp_state to_ib_qp_state(enum mlx5_qp_state mlx5_state) { switch (mlx5_state) { case MLX5_QP_STATE_RST: return IB_QPS_RESET; case MLX5_QP_STATE_INIT: return IB_QPS_INIT; case MLX5_QP_STATE_RTR: return IB_QPS_RTR; case MLX5_QP_STATE_RTS: return IB_QPS_RTS; case MLX5_QP_STATE_SQ_DRAINING: case MLX5_QP_STATE_SQD: return IB_QPS_SQD; case MLX5_QP_STATE_SQER: return IB_QPS_SQE; case MLX5_QP_STATE_ERR: return IB_QPS_ERR; default: return -1; } } static inline enum ib_mig_state to_ib_mig_state(int mlx5_mig_state) { switch (mlx5_mig_state) { case MLX5_QP_PM_ARMED: return IB_MIG_ARMED; case MLX5_QP_PM_REARM: return IB_MIG_REARM; case MLX5_QP_PM_MIGRATED: return IB_MIG_MIGRATED; default: return -1; } } static int to_ib_qp_access_flags(int mlx5_flags) { int ib_flags = 0; if (mlx5_flags & MLX5_QP_BIT_RRE) ib_flags |= IB_ACCESS_REMOTE_READ; if (mlx5_flags & MLX5_QP_BIT_RWE) ib_flags |= IB_ACCESS_REMOTE_WRITE; if (mlx5_flags & MLX5_QP_BIT_RAE) ib_flags |= IB_ACCESS_REMOTE_ATOMIC; return ib_flags; } static void to_rdma_ah_attr(struct mlx5_ib_dev *ibdev, struct rdma_ah_attr *ah_attr, struct mlx5_qp_path *path) { memset(ah_attr, 0, sizeof(*ah_attr)); if (!path->port || path->port > ibdev->num_ports) return; ah_attr->type = rdma_ah_find_type(&ibdev->ib_dev, path->port); rdma_ah_set_port_num(ah_attr, path->port); rdma_ah_set_sl(ah_attr, path->dci_cfi_prio_sl & 0xf); rdma_ah_set_dlid(ah_attr, be16_to_cpu(path->rlid)); rdma_ah_set_path_bits(ah_attr, path->grh_mlid & 0x7f); rdma_ah_set_static_rate(ah_attr, path->static_rate ? path->static_rate - 5 : 0); if (path->grh_mlid & (1 << 7)) { u32 tc_fl = be32_to_cpu(path->tclass_flowlabel); rdma_ah_set_grh(ah_attr, NULL, tc_fl & 0xfffff, path->mgid_index, path->hop_limit, (tc_fl >> 20) & 0xff); rdma_ah_set_dgid_raw(ah_attr, path->rgid); } } static int query_raw_packet_qp_sq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_sq *sq, u8 *sq_state) { int err; err = mlx5_core_query_sq_state(dev->mdev, sq->base.mqp.qpn, sq_state); if (err) goto out; sq->state = *sq_state; out: return err; } static int query_raw_packet_qp_rq_state(struct mlx5_ib_dev *dev, struct mlx5_ib_rq *rq, u8 *rq_state) { void *out; void *rqc; int inlen; int err; inlen = MLX5_ST_SZ_BYTES(query_rq_out); out = kvzalloc(inlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_query_rq(dev->mdev, rq->base.mqp.qpn, out); if (err) goto out; rqc = MLX5_ADDR_OF(query_rq_out, out, rq_context); *rq_state = MLX5_GET(rqc, rqc, state); rq->state = *rq_state; out: kvfree(out); return err; } static int sqrq_state_to_qp_state(u8 sq_state, u8 rq_state, struct mlx5_ib_qp *qp, u8 *qp_state) { static const u8 sqrq_trans[MLX5_RQ_NUM_STATE][MLX5_SQ_NUM_STATE] = { [MLX5_RQC_STATE_RST] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE_BAD, [MLX5_SQ_STATE_NA] = IB_QPS_RESET, }, [MLX5_RQC_STATE_RDY] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = IB_QPS_SQE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE, }, [MLX5_RQC_STATE_ERR] = { [MLX5_SQC_STATE_RST] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE_BAD, [MLX5_SQC_STATE_ERR] = IB_QPS_ERR, [MLX5_SQ_STATE_NA] = IB_QPS_ERR, }, [MLX5_RQ_STATE_NA] = { [MLX5_SQC_STATE_RST] = IB_QPS_RESET, [MLX5_SQC_STATE_RDY] = MLX5_QP_STATE, [MLX5_SQC_STATE_ERR] = MLX5_QP_STATE, [MLX5_SQ_STATE_NA] = MLX5_QP_STATE_BAD, }, }; *qp_state = sqrq_trans[rq_state][sq_state]; if (*qp_state == MLX5_QP_STATE_BAD) { WARN(1, "Buggy Raw Packet QP state, SQ 0x%x state: 0x%x, RQ 0x%x state: 0x%x", qp->raw_packet_qp.sq.base.mqp.qpn, sq_state, qp->raw_packet_qp.rq.base.mqp.qpn, rq_state); return -EINVAL; } if (*qp_state == MLX5_QP_STATE) *qp_state = qp->state; return 0; } static int query_raw_packet_qp_state(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, u8 *raw_packet_qp_state) { struct mlx5_ib_raw_packet_qp *raw_packet_qp = &qp->raw_packet_qp; struct mlx5_ib_sq *sq = &raw_packet_qp->sq; struct mlx5_ib_rq *rq = &raw_packet_qp->rq; int err; u8 sq_state = MLX5_SQ_STATE_NA; u8 rq_state = MLX5_RQ_STATE_NA; if (qp->sq.wqe_cnt) { err = query_raw_packet_qp_sq_state(dev, sq, &sq_state); if (err) return err; } if (qp->rq.wqe_cnt) { err = query_raw_packet_qp_rq_state(dev, rq, &rq_state); if (err) return err; } return sqrq_state_to_qp_state(sq_state, rq_state, qp, raw_packet_qp_state); } static int query_qp_attr(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, struct ib_qp_attr *qp_attr) { int outlen = MLX5_ST_SZ_BYTES(query_qp_out); struct mlx5_qp_context *context; int mlx5_state; u32 *outb; int err = 0; outb = kzalloc(outlen, GFP_KERNEL); if (!outb) return -ENOMEM; err = mlx5_core_qp_query(dev->mdev, &qp->trans_qp.base.mqp, outb, outlen); if (err) goto out; /* FIXME: use MLX5_GET rather than mlx5_qp_context manual struct */ context = (struct mlx5_qp_context *)MLX5_ADDR_OF(query_qp_out, outb, qpc); mlx5_state = be32_to_cpu(context->flags) >> 28; qp->state = to_ib_qp_state(mlx5_state); qp_attr->path_mtu = context->mtu_msgmax >> 5; qp_attr->path_mig_state = to_ib_mig_state((be32_to_cpu(context->flags) >> 11) & 0x3); qp_attr->qkey = be32_to_cpu(context->qkey); qp_attr->rq_psn = be32_to_cpu(context->rnr_nextrecvpsn) & 0xffffff; qp_attr->sq_psn = be32_to_cpu(context->next_send_psn) & 0xffffff; qp_attr->dest_qp_num = be32_to_cpu(context->log_pg_sz_remote_qpn) & 0xffffff; qp_attr->qp_access_flags = to_ib_qp_access_flags(be32_to_cpu(context->params2)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC) { to_rdma_ah_attr(dev, &qp_attr->ah_attr, &context->pri_path); to_rdma_ah_attr(dev, &qp_attr->alt_ah_attr, &context->alt_path); qp_attr->alt_pkey_index = be16_to_cpu(context->alt_path.pkey_index); qp_attr->alt_port_num = rdma_ah_get_port_num(&qp_attr->alt_ah_attr); } qp_attr->pkey_index = be16_to_cpu(context->pri_path.pkey_index); qp_attr->port_num = context->pri_path.port; /* qp_attr->en_sqd_async_notify is only applicable in modify qp */ qp_attr->sq_draining = mlx5_state == MLX5_QP_STATE_SQ_DRAINING; qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context->params1) >> 21) & 0x7); qp_attr->max_dest_rd_atomic = 1 << ((be32_to_cpu(context->params2) >> 21) & 0x7); qp_attr->min_rnr_timer = (be32_to_cpu(context->rnr_nextrecvpsn) >> 24) & 0x1f; qp_attr->timeout = context->pri_path.ackto_lt >> 3; qp_attr->retry_cnt = (be32_to_cpu(context->params1) >> 16) & 0x7; qp_attr->rnr_retry = (be32_to_cpu(context->params1) >> 13) & 0x7; qp_attr->alt_timeout = context->alt_path.ackto_lt >> 3; out: kfree(outb); return err; } static int mlx5_ib_dct_query_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *mqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_core_dct *dct = &mqp->dct.mdct; u32 *out; u32 access_flags = 0; int outlen = MLX5_ST_SZ_BYTES(query_dct_out); void *dctc; int err; int supported_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PORT | IB_QP_MIN_RNR_TIMER | IB_QP_AV | IB_QP_PATH_MTU | IB_QP_PKEY_INDEX; if (qp_attr_mask & ~supported_mask) return -EINVAL; if (mqp->state != IB_QPS_RTR) return -EINVAL; out = kzalloc(outlen, GFP_KERNEL); if (!out) return -ENOMEM; err = mlx5_core_dct_query(dev->mdev, dct, out, outlen); if (err) goto out; dctc = MLX5_ADDR_OF(query_dct_out, out, dct_context_entry); if (qp_attr_mask & IB_QP_STATE) qp_attr->qp_state = IB_QPS_RTR; if (qp_attr_mask & IB_QP_ACCESS_FLAGS) { if (MLX5_GET(dctc, dctc, rre)) access_flags |= IB_ACCESS_REMOTE_READ; if (MLX5_GET(dctc, dctc, rwe)) access_flags |= IB_ACCESS_REMOTE_WRITE; if (MLX5_GET(dctc, dctc, rae)) access_flags |= IB_ACCESS_REMOTE_ATOMIC; qp_attr->qp_access_flags = access_flags; } if (qp_attr_mask & IB_QP_PORT) qp_attr->port_num = MLX5_GET(dctc, dctc, port); if (qp_attr_mask & IB_QP_MIN_RNR_TIMER) qp_attr->min_rnr_timer = MLX5_GET(dctc, dctc, min_rnr_nak); if (qp_attr_mask & IB_QP_AV) { qp_attr->ah_attr.grh.traffic_class = MLX5_GET(dctc, dctc, tclass); qp_attr->ah_attr.grh.flow_label = MLX5_GET(dctc, dctc, flow_label); qp_attr->ah_attr.grh.sgid_index = MLX5_GET(dctc, dctc, my_addr_index); qp_attr->ah_attr.grh.hop_limit = MLX5_GET(dctc, dctc, hop_limit); } if (qp_attr_mask & IB_QP_PATH_MTU) qp_attr->path_mtu = MLX5_GET(dctc, dctc, mtu); if (qp_attr_mask & IB_QP_PKEY_INDEX) qp_attr->pkey_index = MLX5_GET(dctc, dctc, pkey_index); out: kfree(out); return err; } int mlx5_ib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx5_ib_dev *dev = to_mdev(ibqp->device); struct mlx5_ib_qp *qp = to_mqp(ibqp); int err = 0; u8 raw_packet_qp_state; if (ibqp->rwq_ind_tbl) return -ENOSYS; if (unlikely(ibqp->qp_type == IB_QPT_GSI)) return mlx5_ib_gsi_query_qp(ibqp, qp_attr, qp_attr_mask, qp_init_attr); /* Not all of output fields are applicable, make sure to zero them */ memset(qp_init_attr, 0, sizeof(*qp_init_attr)); memset(qp_attr, 0, sizeof(*qp_attr)); if (unlikely(qp->qp_sub_type == MLX5_IB_QPT_DCT)) return mlx5_ib_dct_query_qp(dev, qp, qp_attr, qp_attr_mask, qp_init_attr); mutex_lock(&qp->mutex); if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { err = query_raw_packet_qp_state(dev, qp, &raw_packet_qp_state); if (err) goto out; qp->state = raw_packet_qp_state; qp_attr->port_num = 1; } else { err = query_qp_attr(dev, qp, qp_attr); if (err) goto out; } qp_attr->qp_state = qp->state; qp_attr->cur_qp_state = qp_attr->qp_state; qp_attr->cap.max_recv_wr = qp->rq.wqe_cnt; qp_attr->cap.max_recv_sge = qp->rq.max_gs; if (!ibqp->uobject) { qp_attr->cap.max_send_wr = qp->sq.max_post; qp_attr->cap.max_send_sge = qp->sq.max_gs; qp_init_attr->qp_context = ibqp->qp_context; } else { qp_attr->cap.max_send_wr = 0; qp_attr->cap.max_send_sge = 0; } qp_init_attr->qp_type = ibqp->qp_type; qp_init_attr->recv_cq = ibqp->recv_cq; qp_init_attr->send_cq = ibqp->send_cq; qp_init_attr->srq = ibqp->srq; qp_attr->cap.max_inline_data = qp->max_inline_data; qp_init_attr->cap = qp_attr->cap; qp_init_attr->create_flags = 0; if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) qp_init_attr->create_flags |= IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK; if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) qp_init_attr->create_flags |= IB_QP_CREATE_CROSS_CHANNEL; if (qp->flags & MLX5_IB_QP_MANAGED_SEND) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_SEND; if (qp->flags & MLX5_IB_QP_MANAGED_RECV) qp_init_attr->create_flags |= IB_QP_CREATE_MANAGED_RECV; if (qp->flags & MLX5_IB_QP_SQPN_QP1) qp_init_attr->create_flags |= mlx5_ib_create_qp_sqpn_qp1(); qp_init_attr->sq_sig_type = qp->sq_signal_bits & MLX5_WQE_CTRL_CQ_UPDATE ? IB_SIGNAL_ALL_WR : IB_SIGNAL_REQ_WR; out: mutex_unlock(&qp->mutex); return err; } struct ib_xrcd *mlx5_ib_alloc_xrcd(struct ib_device *ibdev, struct ib_ucontext *context, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(ibdev); struct mlx5_ib_xrcd *xrcd; int err; if (!MLX5_CAP_GEN(dev->mdev, xrc)) return ERR_PTR(-ENOSYS); xrcd = kmalloc(sizeof(*xrcd), GFP_KERNEL); if (!xrcd) return ERR_PTR(-ENOMEM); err = mlx5_core_xrcd_alloc(dev->mdev, &xrcd->xrcdn); if (err) { kfree(xrcd); return ERR_PTR(-ENOMEM); } return &xrcd->ibxrcd; } int mlx5_ib_dealloc_xrcd(struct ib_xrcd *xrcd) { struct mlx5_ib_dev *dev = to_mdev(xrcd->device); u32 xrcdn = to_mxrcd(xrcd)->xrcdn; int err; err = mlx5_core_xrcd_dealloc(dev->mdev, xrcdn); if (err) mlx5_ib_warn(dev, "failed to dealloc xrcdn 0x%x\n", xrcdn); kfree(xrcd); return 0; } static void mlx5_ib_wq_event(struct mlx5_core_qp *core_qp, int type) { struct mlx5_ib_rwq *rwq = to_mibrwq(core_qp); struct mlx5_ib_dev *dev = to_mdev(rwq->ibwq.device); struct ib_event event; if (rwq->ibwq.event_handler) { event.device = rwq->ibwq.device; event.element.wq = &rwq->ibwq; switch (type) { case MLX5_EVENT_TYPE_WQ_CATAS_ERROR: event.event = IB_EVENT_WQ_FATAL; break; default: mlx5_ib_warn(dev, "Unexpected event type %d on WQ %06x\n", type, core_qp->qpn); return; } rwq->ibwq.event_handler(&event, rwq->ibwq.wq_context); } } static int set_delay_drop(struct mlx5_ib_dev *dev) { int err = 0; mutex_lock(&dev->delay_drop.lock); if (dev->delay_drop.activate) goto out; err = mlx5_core_set_delay_drop(dev->mdev, dev->delay_drop.timeout); if (err) goto out; dev->delay_drop.activate = true; out: mutex_unlock(&dev->delay_drop.lock); if (!err) atomic_inc(&dev->delay_drop.rqs_cnt); return err; } static int create_rq(struct mlx5_ib_rwq *rwq, struct ib_pd *pd, struct ib_wq_init_attr *init_attr) { struct mlx5_ib_dev *dev; int has_net_offloads; __be64 *rq_pas0; void *in; void *rqc; void *wq; int inlen; int err; dev = to_mdev(pd->device); inlen = MLX5_ST_SZ_BYTES(create_rq_in) + sizeof(u64) * rwq->rq_num_pas; in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(create_rq_in, in, ctx); MLX5_SET(rqc, rqc, mem_rq_type, MLX5_RQC_MEM_RQ_TYPE_MEMORY_RQ_INLINE); MLX5_SET(rqc, rqc, user_index, rwq->user_index); MLX5_SET(rqc, rqc, cqn, to_mcq(init_attr->cq)->mcq.cqn); MLX5_SET(rqc, rqc, state, MLX5_RQC_STATE_RST); MLX5_SET(rqc, rqc, flush_in_error_en, 1); wq = MLX5_ADDR_OF(rqc, rqc, wq); MLX5_SET(wq, wq, wq_type, rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ ? MLX5_WQ_TYPE_CYCLIC_STRIDING_RQ : MLX5_WQ_TYPE_CYCLIC); if (init_attr->create_flags & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "Scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } else { MLX5_SET(wq, wq, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } } MLX5_SET(wq, wq, log_wq_stride, rwq->log_rq_stride); if (rwq->create_flags & MLX5_IB_WQ_FLAGS_STRIDING_RQ) { MLX5_SET(wq, wq, two_byte_shift_en, rwq->two_byte_shift_en); MLX5_SET(wq, wq, log_wqe_stride_size, rwq->single_stride_log_num_of_bytes - MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES); MLX5_SET(wq, wq, log_wqe_num_of_strides, rwq->log_num_strides - MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES); } MLX5_SET(wq, wq, log_wq_sz, rwq->log_rq_size); MLX5_SET(wq, wq, pd, to_mpd(pd)->pdn); MLX5_SET(wq, wq, page_offset, rwq->rq_page_offset); MLX5_SET(wq, wq, log_wq_pg_sz, rwq->log_page_size); MLX5_SET(wq, wq, wq_signature, rwq->wq_sig); MLX5_SET64(wq, wq, dbr_addr, rwq->db.dma); has_net_offloads = MLX5_CAP_GEN(dev->mdev, eth_net_offloads); if (init_attr->create_flags & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not supported\n"); err = -EOPNOTSUPP; goto out; } } else { MLX5_SET(rqc, rqc, vsd, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_SCATTER_FCS) { if (!(has_net_offloads && MLX5_CAP_ETH(dev->mdev, scatter_fcs))) { mlx5_ib_dbg(dev, "Scatter FCS is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, scatter_fcs, 1); } if (init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { if (!(dev->ib_dev.attrs.raw_packet_caps & IB_RAW_PACKET_CAP_DELAY_DROP)) { mlx5_ib_dbg(dev, "Delay drop is not supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET(rqc, rqc, delay_drop_en, 1); } rq_pas0 = (__be64 *)MLX5_ADDR_OF(wq, wq, pas); mlx5_ib_populate_pas(dev, rwq->umem, rwq->page_shift, rq_pas0, 0); err = mlx5_core_create_rq_tracked(dev->mdev, in, inlen, &rwq->core_qp); if (!err && init_attr->create_flags & IB_WQ_FLAGS_DELAY_DROP) { err = set_delay_drop(dev); if (err) { mlx5_ib_warn(dev, "Failed to enable delay drop err=%d\n", err); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); } else { rwq->create_flags |= MLX5_IB_WQ_FLAGS_DELAY_DROP; } } out: kvfree(in); return err; } static int set_user_rq_size(struct mlx5_ib_dev *dev, struct ib_wq_init_attr *wq_init_attr, struct mlx5_ib_create_wq *ucmd, struct mlx5_ib_rwq *rwq) { /* Sanity check RQ size before proceeding */ if (wq_init_attr->max_wr > (1 << MLX5_CAP_GEN(dev->mdev, log_max_wq_sz))) return -EINVAL; if (!ucmd->rq_wqe_count) return -EINVAL; rwq->wqe_count = ucmd->rq_wqe_count; rwq->wqe_shift = ucmd->rq_wqe_shift; if (check_shl_overflow(rwq->wqe_count, rwq->wqe_shift, &rwq->buf_size)) return -EINVAL; rwq->log_rq_stride = rwq->wqe_shift; rwq->log_rq_size = ilog2(rwq->wqe_count); return 0; } static int prepare_user_rq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_rwq *rwq) { struct mlx5_ib_dev *dev = to_mdev(pd->device); struct mlx5_ib_create_wq ucmd = {}; int err; size_t required_cmd_sz; required_cmd_sz = offsetof(typeof(ucmd), single_stride_log_num_of_bytes) + sizeof(ucmd.single_stride_log_num_of_bytes); if (udata->inlen < required_cmd_sz) { mlx5_ib_dbg(dev, "invalid inlen\n"); return -EINVAL; } if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) { mlx5_ib_dbg(dev, "inlen is not supported\n"); return -EOPNOTSUPP; } if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } if (ucmd.comp_mask & (~MLX5_IB_CREATE_WQ_STRIDING_RQ)) { mlx5_ib_dbg(dev, "invalid comp mask\n"); return -EOPNOTSUPP; } else if (ucmd.comp_mask & MLX5_IB_CREATE_WQ_STRIDING_RQ) { if (!MLX5_CAP_GEN(dev->mdev, striding_rq)) { mlx5_ib_dbg(dev, "Striding RQ is not supported\n"); return -EOPNOTSUPP; } if ((ucmd.single_stride_log_num_of_bytes < MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES) || (ucmd.single_stride_log_num_of_bytes > MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES)) { mlx5_ib_dbg(dev, "Invalid log stride size (%u. Range is %u - %u)\n", ucmd.single_stride_log_num_of_bytes, MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES, MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES); return -EINVAL; } if ((ucmd.single_wqe_log_num_of_strides > MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES) || (ucmd.single_wqe_log_num_of_strides < MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES)) { mlx5_ib_dbg(dev, "Invalid log num strides (%u. Range is %u - %u)\n", ucmd.single_wqe_log_num_of_strides, MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES, MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES); return -EINVAL; } rwq->single_stride_log_num_of_bytes = ucmd.single_stride_log_num_of_bytes; rwq->log_num_strides = ucmd.single_wqe_log_num_of_strides; rwq->two_byte_shift_en = !!ucmd.two_byte_shift_en; rwq->create_flags |= MLX5_IB_WQ_FLAGS_STRIDING_RQ; } err = set_user_rq_size(dev, init_attr, &ucmd, rwq); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } err = create_user_rq(dev, pd, rwq, &ucmd); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); if (err) return err; } rwq->user_index = ucmd.user_index; return 0; } struct ib_wq *mlx5_ib_create_wq(struct ib_pd *pd, struct ib_wq_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev; struct mlx5_ib_rwq *rwq; struct mlx5_ib_create_wq_resp resp = {}; size_t min_resp_len; int err; if (!udata) return ERR_PTR(-ENOSYS); min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); dev = to_mdev(pd->device); switch (init_attr->wq_type) { case IB_WQT_RQ: rwq = kzalloc(sizeof(*rwq), GFP_KERNEL); if (!rwq) return ERR_PTR(-ENOMEM); err = prepare_user_rq(pd, init_attr, udata, rwq); if (err) goto err; err = create_rq(rwq, pd, init_attr); if (err) goto err_user_rq; break; default: mlx5_ib_dbg(dev, "unsupported wq type %d\n", init_attr->wq_type); return ERR_PTR(-EINVAL); } rwq->ibwq.wq_num = rwq->core_qp.qpn; rwq->ibwq.state = IB_WQS_RESET; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } rwq->core_qp.event = mlx5_ib_wq_event; rwq->ibwq.event_handler = init_attr->event_handler; return &rwq->ibwq; err_copy: mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); err_user_rq: destroy_user_rq(dev, pd, rwq); err: kfree(rwq); return ERR_PTR(err); } int mlx5_ib_destroy_wq(struct ib_wq *wq) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); mlx5_core_destroy_rq_tracked(dev->mdev, &rwq->core_qp); destroy_user_rq(dev, wq->pd, rwq); kfree(rwq); return 0; } struct ib_rwq_ind_table *mlx5_ib_create_rwq_ind_table(struct ib_device *device, struct ib_rwq_ind_table_init_attr *init_attr, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(device); struct mlx5_ib_rwq_ind_table *rwq_ind_tbl; int sz = 1 << init_attr->log_ind_tbl_size; struct mlx5_ib_create_rwq_ind_tbl_resp resp = {}; size_t min_resp_len; int inlen; int err; int i; u32 *in; void *rqtc; if (udata->inlen > 0 && !ib_is_udata_cleared(udata, 0, udata->inlen)) return ERR_PTR(-EOPNOTSUPP); if (init_attr->log_ind_tbl_size > MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)) { mlx5_ib_dbg(dev, "log_ind_tbl_size = %d is bigger than supported = %d\n", init_attr->log_ind_tbl_size, MLX5_CAP_GEN(dev->mdev, log_max_rqt_size)); return ERR_PTR(-EINVAL); } min_resp_len = offsetof(typeof(resp), reserved) + sizeof(resp.reserved); if (udata->outlen && udata->outlen < min_resp_len) return ERR_PTR(-EINVAL); rwq_ind_tbl = kzalloc(sizeof(*rwq_ind_tbl), GFP_KERNEL); if (!rwq_ind_tbl) return ERR_PTR(-ENOMEM); inlen = MLX5_ST_SZ_BYTES(create_rqt_in) + sizeof(u32) * sz; in = kvzalloc(inlen, GFP_KERNEL); if (!in) { err = -ENOMEM; goto err; } rqtc = MLX5_ADDR_OF(create_rqt_in, in, rqt_context); MLX5_SET(rqtc, rqtc, rqt_actual_size, sz); MLX5_SET(rqtc, rqtc, rqt_max_size, sz); for (i = 0; i < sz; i++) MLX5_SET(rqtc, rqtc, rq_num[i], init_attr->ind_tbl[i]->wq_num); err = mlx5_core_create_rqt(dev->mdev, in, inlen, &rwq_ind_tbl->rqtn); kvfree(in); if (err) goto err; rwq_ind_tbl->ib_rwq_ind_tbl.ind_tbl_num = rwq_ind_tbl->rqtn; if (udata->outlen) { resp.response_length = offsetof(typeof(resp), response_length) + sizeof(resp.response_length); err = ib_copy_to_udata(udata, &resp, resp.response_length); if (err) goto err_copy; } return &rwq_ind_tbl->ib_rwq_ind_tbl; err_copy: mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); err: kfree(rwq_ind_tbl); return ERR_PTR(err); } int mlx5_ib_destroy_rwq_ind_table(struct ib_rwq_ind_table *ib_rwq_ind_tbl) { struct mlx5_ib_rwq_ind_table *rwq_ind_tbl = to_mrwq_ind_table(ib_rwq_ind_tbl); struct mlx5_ib_dev *dev = to_mdev(ib_rwq_ind_tbl->device); mlx5_core_destroy_rqt(dev->mdev, rwq_ind_tbl->rqtn); kfree(rwq_ind_tbl); return 0; } int mlx5_ib_modify_wq(struct ib_wq *wq, struct ib_wq_attr *wq_attr, u32 wq_attr_mask, struct ib_udata *udata) { struct mlx5_ib_dev *dev = to_mdev(wq->device); struct mlx5_ib_rwq *rwq = to_mrwq(wq); struct mlx5_ib_modify_wq ucmd = {}; size_t required_cmd_sz; int curr_wq_state; int wq_state; int inlen; int err; void *rqc; void *in; required_cmd_sz = offsetof(typeof(ucmd), reserved) + sizeof(ucmd.reserved); if (udata->inlen < required_cmd_sz) return -EINVAL; if (udata->inlen > sizeof(ucmd) && !ib_is_udata_cleared(udata, sizeof(ucmd), udata->inlen - sizeof(ucmd))) return -EOPNOTSUPP; if (ib_copy_from_udata(&ucmd, udata, min(sizeof(ucmd), udata->inlen))) return -EFAULT; if (ucmd.comp_mask || ucmd.reserved) return -EOPNOTSUPP; inlen = MLX5_ST_SZ_BYTES(modify_rq_in); in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; rqc = MLX5_ADDR_OF(modify_rq_in, in, ctx); curr_wq_state = (wq_attr_mask & IB_WQ_CUR_STATE) ? wq_attr->curr_wq_state : wq->state; wq_state = (wq_attr_mask & IB_WQ_STATE) ? wq_attr->wq_state : curr_wq_state; if (curr_wq_state == IB_WQS_ERR) curr_wq_state = MLX5_RQC_STATE_ERR; if (wq_state == IB_WQS_ERR) wq_state = MLX5_RQC_STATE_ERR; MLX5_SET(modify_rq_in, in, rq_state, curr_wq_state); MLX5_SET(rqc, rqc, state, wq_state); if (wq_attr_mask & IB_WQ_FLAGS) { if (wq_attr->flags_mask & IB_WQ_FLAGS_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap))) { mlx5_ib_dbg(dev, "VLAN offloads are not " "supported\n"); err = -EOPNOTSUPP; goto out; } MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_VSD); MLX5_SET(rqc, rqc, vsd, (wq_attr->flags & IB_WQ_FLAGS_CVLAN_STRIPPING) ? 0 : 1); } if (wq_attr->flags_mask & IB_WQ_FLAGS_PCI_WRITE_END_PADDING) { mlx5_ib_dbg(dev, "Modifying scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto out; } } if (curr_wq_state == IB_WQS_RESET && wq_state == IB_WQS_RDY) { if (MLX5_CAP_GEN(dev->mdev, modify_rq_counter_set_id)) { MLX5_SET64(modify_rq_in, in, modify_bitmask, MLX5_MODIFY_RQ_IN_MODIFY_BITMASK_RQ_COUNTER_SET_ID); MLX5_SET(rqc, rqc, counter_set_id, dev->port->cnts.set_id); } else pr_info_once("%s: Receive WQ counters are not supported on current FW\n", dev->ib_dev.name); } err = mlx5_core_modify_rq(dev->mdev, rwq->core_qp.qpn, in, inlen); if (!err) rwq->ibwq.state = (wq_state == MLX5_RQC_STATE_ERR) ? IB_WQS_ERR : wq_state; out: kvfree(in); return err; } struct mlx5_ib_drain_cqe { struct ib_cqe cqe; struct completion done; }; static void mlx5_ib_drain_qp_done(struct ib_cq *cq, struct ib_wc *wc) { struct mlx5_ib_drain_cqe *cqe = container_of(wc->wr_cqe, struct mlx5_ib_drain_cqe, cqe); complete(&cqe->done); } /* This function returns only once the drained WR was completed */ static void handle_drain_completion(struct ib_cq *cq, struct mlx5_ib_drain_cqe *sdrain, struct mlx5_ib_dev *dev) { struct mlx5_core_dev *mdev = dev->mdev; if (cq->poll_ctx == IB_POLL_DIRECT) { while (wait_for_completion_timeout(&sdrain->done, HZ / 10) <= 0) ib_process_cq_direct(cq, -1); return; } if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) { struct mlx5_ib_cq *mcq = to_mcq(cq); bool triggered = false; unsigned long flags; spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); /* Make sure that the CQ handler won't run if wasn't run yet */ if (!mcq->mcq.reset_notify_added) mcq->mcq.reset_notify_added = 1; else triggered = true; spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); if (triggered) { /* Wait for any scheduled/running task to be ended */ switch (cq->poll_ctx) { case IB_POLL_SOFTIRQ: irq_poll_disable(&cq->iop); irq_poll_enable(&cq->iop); break; case IB_POLL_WORKQUEUE: cancel_work_sync(&cq->work); break; default: WARN_ON_ONCE(1); } } /* Run the CQ handler - this makes sure that the drain WR will * be processed if wasn't processed yet. */ mcq->mcq.comp(&mcq->mcq); } wait_for_completion(&sdrain->done); } void mlx5_ib_drain_sq(struct ib_qp *qp) { struct ib_cq *cq = qp->send_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe sdrain; const struct ib_send_wr *bad_swr; struct ib_rdma_wr swr = { .wr = { .next = NULL, { .wr_cqe = &sdrain.cqe, }, .opcode = IB_WR_RDMA_WRITE, }, }; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } sdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&sdrain.done); ret = _mlx5_ib_post_send(qp, &swr.wr, &bad_swr, true); if (ret) { WARN_ONCE(ret, "failed to drain send queue: %d\n", ret); return; } handle_drain_completion(cq, &sdrain, dev); } void mlx5_ib_drain_rq(struct ib_qp *qp) { struct ib_cq *cq = qp->recv_cq; struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR }; struct mlx5_ib_drain_cqe rdrain; struct ib_recv_wr rwr = {}; const struct ib_recv_wr *bad_rwr; int ret; struct mlx5_ib_dev *dev = to_mdev(qp->device); struct mlx5_core_dev *mdev = dev->mdev; ret = ib_modify_qp(qp, &attr, IB_QP_STATE); if (ret && mdev->state != MLX5_DEVICE_STATE_INTERNAL_ERROR) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } rwr.wr_cqe = &rdrain.cqe; rdrain.cqe.done = mlx5_ib_drain_qp_done; init_completion(&rdrain.done); ret = _mlx5_ib_post_recv(qp, &rwr, &bad_rwr, true); if (ret) { WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret); return; } handle_drain_completion(cq, &rdrain, dev); }
static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; }
static int create_qp_common(struct mlx5_ib_dev *dev, struct ib_pd *pd, struct ib_qp_init_attr *init_attr, struct ib_udata *udata, struct mlx5_ib_qp *qp) { struct mlx5_ib_resources *devr = &dev->devr; int inlen = MLX5_ST_SZ_BYTES(create_qp_in); struct mlx5_core_dev *mdev = dev->mdev; struct mlx5_ib_create_qp_resp resp = {}; struct mlx5_ib_cq *send_cq; struct mlx5_ib_cq *recv_cq; unsigned long flags; u32 uidx = MLX5_IB_DEFAULT_UIDX; struct mlx5_ib_create_qp ucmd; struct mlx5_ib_qp_base *base; int mlx5_st; void *qpc; u32 *in; int err; mutex_init(&qp->mutex); spin_lock_init(&qp->sq.lock); spin_lock_init(&qp->rq.lock); mlx5_st = to_mlx5_st(init_attr->qp_type); if (mlx5_st < 0) return -EINVAL; if (init_attr->rwq_ind_tbl) { if (!udata) return -ENOSYS; err = create_rss_raw_qp_tir(dev, qp, pd, init_attr, udata); return err; } if (init_attr->create_flags & IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK) { if (!MLX5_CAP_GEN(mdev, block_lb_mc)) { mlx5_ib_dbg(dev, "block multicast loopback isn't supported\n"); return -EINVAL; } else { qp->flags |= MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK; } } if (init_attr->create_flags & (IB_QP_CREATE_CROSS_CHANNEL | IB_QP_CREATE_MANAGED_SEND | IB_QP_CREATE_MANAGED_RECV)) { if (!MLX5_CAP_GEN(mdev, cd)) { mlx5_ib_dbg(dev, "cross-channel isn't supported\n"); return -EINVAL; } if (init_attr->create_flags & IB_QP_CREATE_CROSS_CHANNEL) qp->flags |= MLX5_IB_QP_CROSS_CHANNEL; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_SEND) qp->flags |= MLX5_IB_QP_MANAGED_SEND; if (init_attr->create_flags & IB_QP_CREATE_MANAGED_RECV) qp->flags |= MLX5_IB_QP_MANAGED_RECV; } if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) if (!MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) { mlx5_ib_dbg(dev, "ipoib UD lso qp isn't supported\n"); return -EOPNOTSUPP; } if (init_attr->create_flags & IB_QP_CREATE_SCATTER_FCS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET) { mlx5_ib_dbg(dev, "Scatter FCS is supported only for Raw Packet QPs"); return -EOPNOTSUPP; } if (!MLX5_CAP_GEN(dev->mdev, eth_net_offloads) || !MLX5_CAP_ETH(dev->mdev, scatter_fcs)) { mlx5_ib_dbg(dev, "Scatter FCS isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_CAP_SCATTER_FCS; } if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) qp->sq_signal_bits = MLX5_WQE_CTRL_CQ_UPDATE; if (init_attr->create_flags & IB_QP_CREATE_CVLAN_STRIPPING) { if (!(MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && MLX5_CAP_ETH(dev->mdev, vlan_cap)) || (init_attr->qp_type != IB_QPT_RAW_PACKET)) return -EOPNOTSUPP; qp->flags |= MLX5_IB_QP_CVLAN_STRIPPING; } if (pd && pd->uobject) { if (ib_copy_from_udata(&ucmd, udata, sizeof(ucmd))) { mlx5_ib_dbg(dev, "copy failed\n"); return -EFAULT; } err = get_qp_user_index(to_mucontext(pd->uobject->context), &ucmd, udata->inlen, &uidx); if (err) return err; qp->wq_sig = !!(ucmd.flags & MLX5_QP_FLAG_SIGNATURE); qp->scat_cqe = !!(ucmd.flags & MLX5_QP_FLAG_SCATTER_CQE); if (ucmd.flags & MLX5_QP_FLAG_TUNNEL_OFFLOADS) { if (init_attr->qp_type != IB_QPT_RAW_PACKET || !tunnel_offload_supported(mdev)) { mlx5_ib_dbg(dev, "Tunnel offload isn't supported\n"); return -EOPNOTSUPP; } qp->tunnel_offload_en = true; } if (init_attr->create_flags & IB_QP_CREATE_SOURCE_QPN) { if (init_attr->qp_type != IB_QPT_UD || (MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_IB) || !mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS)) { mlx5_ib_dbg(dev, "Source QP option isn't supported\n"); return -EOPNOTSUPP; } qp->flags |= MLX5_IB_QP_UNDERLAY; qp->underlay_qpn = init_attr->source_qpn; } } else { qp->wq_sig = !!wq_signature; } base = (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) ? &qp->raw_packet_qp.rq.base : &qp->trans_qp.base; qp->has_rq = qp_has_rq(init_attr); err = set_rq_size(dev, &init_attr->cap, qp->has_rq, qp, (pd && pd->uobject) ? &ucmd : NULL); if (err) { mlx5_ib_dbg(dev, "err %d\n", err); return err; } if (pd) { if (pd->uobject) { __u32 max_wqes = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz); mlx5_ib_dbg(dev, "requested sq_wqe_count (%d)\n", ucmd.sq_wqe_count); if (ucmd.rq_wqe_shift != qp->rq.wqe_shift || ucmd.rq_wqe_count != qp->rq.wqe_cnt) { mlx5_ib_dbg(dev, "invalid rq params\n"); return -EINVAL; } if (ucmd.sq_wqe_count > max_wqes) { mlx5_ib_dbg(dev, "requested sq_wqe_count (%d) > max allowed (%d)\n", ucmd.sq_wqe_count, max_wqes); return -EINVAL; } if (init_attr->create_flags & mlx5_ib_create_qp_sqpn_qp1()) { mlx5_ib_dbg(dev, "user-space is not allowed to create UD QPs spoofing as QP1\n"); return -EINVAL; } err = create_user_qp(dev, pd, qp, udata, init_attr, &in, &resp, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } else { err = create_kernel_qp(dev, init_attr, qp, &in, &inlen, base); if (err) mlx5_ib_dbg(dev, "err %d\n", err); } if (err) return err; } else { in = kvzalloc(inlen, GFP_KERNEL); if (!in) return -ENOMEM; qp->create_type = MLX5_QP_EMPTY; } if (is_sqp(init_attr->qp_type)) qp->port = init_attr->port_num; qpc = MLX5_ADDR_OF(create_qp_in, in, qpc); MLX5_SET(qpc, qpc, st, mlx5_st); MLX5_SET(qpc, qpc, pm_state, MLX5_QP_PM_MIGRATED); if (init_attr->qp_type != MLX5_IB_QPT_REG_UMR) MLX5_SET(qpc, qpc, pd, to_mpd(pd ? pd : devr->p0)->pdn); else MLX5_SET(qpc, qpc, latency_sensitive, 1); if (qp->wq_sig) MLX5_SET(qpc, qpc, wq_signature, 1); if (qp->flags & MLX5_IB_QP_BLOCK_MULTICAST_LOOPBACK) MLX5_SET(qpc, qpc, block_lb_mc, 1); if (qp->flags & MLX5_IB_QP_CROSS_CHANNEL) MLX5_SET(qpc, qpc, cd_master, 1); if (qp->flags & MLX5_IB_QP_MANAGED_SEND) MLX5_SET(qpc, qpc, cd_slave_send, 1); if (qp->flags & MLX5_IB_QP_MANAGED_RECV) MLX5_SET(qpc, qpc, cd_slave_receive, 1); if (qp->scat_cqe && is_connected(init_attr->qp_type)) { int rcqe_sz; int scqe_sz; rcqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->recv_cq); scqe_sz = mlx5_ib_get_cqe_size(dev, init_attr->send_cq); if (rcqe_sz == 128) MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_res, MLX5_RES_SCAT_DATA32_CQE); if (init_attr->sq_sig_type == IB_SIGNAL_ALL_WR) { if (scqe_sz == 128) MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA64_CQE); else MLX5_SET(qpc, qpc, cs_req, MLX5_REQ_SCAT_DATA32_CQE); } } if (qp->rq.wqe_cnt) { MLX5_SET(qpc, qpc, log_rq_stride, qp->rq.wqe_shift - 4); MLX5_SET(qpc, qpc, log_rq_size, ilog2(qp->rq.wqe_cnt)); } MLX5_SET(qpc, qpc, rq_type, get_rx_type(qp, init_attr)); if (qp->sq.wqe_cnt) { MLX5_SET(qpc, qpc, log_sq_size, ilog2(qp->sq.wqe_cnt)); } else { MLX5_SET(qpc, qpc, no_sq, 1); if (init_attr->srq && init_attr->srq->srq_type == IB_SRQT_TM) MLX5_SET(qpc, qpc, offload_type, MLX5_QPC_OFFLOAD_TYPE_RNDV); } /* Set default resources */ switch (init_attr->qp_type) { case IB_QPT_XRC_TGT: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, cqn_snd, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(init_attr->xrcd)->xrcdn); break; case IB_QPT_XRC_INI: MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(devr->c0)->mcq.cqn); MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s0)->msrq.srqn); break; default: if (init_attr->srq) { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x0)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(init_attr->srq)->msrq.srqn); } else { MLX5_SET(qpc, qpc, xrcd, to_mxrcd(devr->x1)->xrcdn); MLX5_SET(qpc, qpc, srqn_rmpn_xrqn, to_msrq(devr->s1)->msrq.srqn); } } if (init_attr->send_cq) MLX5_SET(qpc, qpc, cqn_snd, to_mcq(init_attr->send_cq)->mcq.cqn); if (init_attr->recv_cq) MLX5_SET(qpc, qpc, cqn_rcv, to_mcq(init_attr->recv_cq)->mcq.cqn); MLX5_SET64(qpc, qpc, dbr_addr, qp->db.dma); /* 0xffffff means we ask to work with cqe version 0 */ if (MLX5_CAP_GEN(mdev, cqe_version) == MLX5_CQE_VERSION_V1) MLX5_SET(qpc, qpc, user_index, uidx); /* we use IB_QP_CREATE_IPOIB_UD_LSO to indicates ipoib qp */ if (init_attr->qp_type == IB_QPT_UD && (init_attr->create_flags & IB_QP_CREATE_IPOIB_UD_LSO)) { MLX5_SET(qpc, qpc, ulp_stateless_offload_mode, 1); qp->flags |= MLX5_IB_QP_LSO; } if (init_attr->create_flags & IB_QP_CREATE_PCI_WRITE_END_PADDING) { if (!MLX5_CAP_GEN(dev->mdev, end_pad)) { mlx5_ib_dbg(dev, "scatter end padding is not supported\n"); err = -EOPNOTSUPP; goto err; } else if (init_attr->qp_type != IB_QPT_RAW_PACKET) { MLX5_SET(qpc, qpc, end_padding_mode, MLX5_WQ_END_PAD_MODE_ALIGN); } else { qp->flags |= MLX5_IB_QP_PCI_WRITE_END_PADDING; } } if (inlen < 0) { err = -EINVAL; goto err; } if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & MLX5_IB_QP_UNDERLAY) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd.sq_buf_addr; raw_packet_qp_copy_info(qp, &qp->raw_packet_qp); err = create_raw_packet_qp(dev, qp, in, inlen, pd); } else { err = mlx5_core_create_qp(dev->mdev, &base->mqp, in, inlen); } if (err) { mlx5_ib_dbg(dev, "create qp failed\n"); goto err_create; } kvfree(in); base->container_mibqp = qp; base->mqp.event = mlx5_ib_qp_event; get_cqs(init_attr->qp_type, init_attr->send_cq, init_attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); mlx5_ib_lock_cqs(send_cq, recv_cq); /* Maintain device to QPs access, needed for further handling via reset * flow */ list_add_tail(&qp->qps_list, &dev->qp_list); /* Maintain CQ to QPs access, needed for further handling via reset flow */ if (send_cq) list_add_tail(&qp->cq_send_list, &send_cq->list_send_qp); if (recv_cq) list_add_tail(&qp->cq_recv_list, &recv_cq->list_recv_qp); mlx5_ib_unlock_cqs(send_cq, recv_cq); spin_unlock_irqrestore(&dev->reset_flow_resource_lock, flags); return 0; err_create: if (qp->create_type == MLX5_QP_USER) destroy_qp_user(dev, pd, qp, base); else if (qp->create_type == MLX5_QP_KERNEL) destroy_qp_kernel(dev, qp); err: kvfree(in); return err; }
{'added': [(1610, '\tstruct mlx5_ib_create_qp_resp resp = {};')], 'deleted': [(1610, '\tstruct mlx5_ib_create_qp_resp resp;')]}
1
1
4,769
32,165
https://github.com/torvalds/linux
CVE-2018-20855
['CWE-119']
idctdsp.c
ff_idctdsp_init
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "libavutil/attributes.h" #include "libavutil/common.h" #include "avcodec.h" #include "dct.h" #include "faanidct.h" #include "idctdsp.h" #include "simple_idct.h" #include "xvididct.h" av_cold void ff_init_scantable(uint8_t *permutation, ScanTable *st, const uint8_t *src_scantable) { int i, end; st->scantable = src_scantable; for (i = 0; i < 64; i++) { int j = src_scantable[i]; st->permutated[i] = permutation[j]; } end = -1; for (i = 0; i < 64; i++) { int j = st->permutated[i]; if (j > end) end = j; st->raster_end[i] = end; } } av_cold void ff_init_scantable_permutation(uint8_t *idct_permutation, enum idct_permutation_type perm_type) { int i; if (ARCH_X86) if (ff_init_scantable_permutation_x86(idct_permutation, perm_type)) return; switch (perm_type) { case FF_IDCT_PERM_NONE: for (i = 0; i < 64; i++) idct_permutation[i] = i; break; case FF_IDCT_PERM_LIBMPEG2: for (i = 0; i < 64; i++) idct_permutation[i] = (i & 0x38) | ((i & 6) >> 1) | ((i & 1) << 2); break; case FF_IDCT_PERM_TRANSPOSE: for (i = 0; i < 64; i++) idct_permutation[i] = ((i & 7) << 3) | (i >> 3); break; case FF_IDCT_PERM_PARTTRANS: for (i = 0; i < 64; i++) idct_permutation[i] = (i & 0x24) | ((i & 3) << 3) | ((i >> 3) & 3); break; default: av_log(NULL, AV_LOG_ERROR, "Internal error, IDCT permutation not set\n"); } } void ff_put_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i; /* read the pixels */ for (i = 0; i < 8; i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels[2] = av_clip_uint8(block[2]); pixels[3] = av_clip_uint8(block[3]); pixels[4] = av_clip_uint8(block[4]); pixels[5] = av_clip_uint8(block[5]); pixels[6] = av_clip_uint8(block[6]); pixels[7] = av_clip_uint8(block[7]); pixels += line_size; block += 8; } } static void put_pixels_clamped4_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<4;i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels[2] = av_clip_uint8(block[2]); pixels[3] = av_clip_uint8(block[3]); pixels += line_size; block += 8; } } static void put_pixels_clamped2_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<2;i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels += line_size; block += 8; } } static void put_signed_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { if (*block < -128) *pixels = 0; else if (*block > 127) *pixels = 255; else *pixels = (uint8_t) (*block + 128); block++; pixels++; } pixels += (line_size - 8); } } void ff_add_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i; /* read the pixels */ for (i = 0; i < 8; i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels[2] = av_clip_uint8(pixels[2] + block[2]); pixels[3] = av_clip_uint8(pixels[3] + block[3]); pixels[4] = av_clip_uint8(pixels[4] + block[4]); pixels[5] = av_clip_uint8(pixels[5] + block[5]); pixels[6] = av_clip_uint8(pixels[6] + block[6]); pixels[7] = av_clip_uint8(pixels[7] + block[7]); pixels += line_size; block += 8; } } static void add_pixels_clamped4_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<4;i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels[2] = av_clip_uint8(pixels[2] + block[2]); pixels[3] = av_clip_uint8(pixels[3] + block[3]); pixels += line_size; block += 8; } } static void add_pixels_clamped2_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<2;i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels += line_size; block += 8; } } static void ff_jref_idct4_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct4 (block); put_pixels_clamped4_c(block, dest, line_size); } static void ff_jref_idct4_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct4 (block); add_pixels_clamped4_c(block, dest, line_size); } static void ff_jref_idct2_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct2 (block); put_pixels_clamped2_c(block, dest, line_size); } static void ff_jref_idct2_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct2 (block); add_pixels_clamped2_c(block, dest, line_size); } static void ff_jref_idct1_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { dest[0] = av_clip_uint8((block[0] + 4)>>3); } static void ff_jref_idct1_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { dest[0] = av_clip_uint8(dest[0] + ((block[0] + 4)>>3)); } av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) { const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; if (avctx->lowres==1) { c->idct_put = ff_jref_idct4_put; c->idct_add = ff_jref_idct4_add; c->idct = ff_j_rev_dct4; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==2) { c->idct_put = ff_jref_idct2_put; c->idct_add = ff_jref_idct2_add; c->idct = ff_j_rev_dct2; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==3) { c->idct_put = ff_jref_idct1_put; c->idct_add = ff_jref_idct1_add; c->idct = ff_j_rev_dct1; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT However, it only uses idct_put */ if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO) c->idct_put = ff_simple_idct_put_int32_10bit; else { c->idct_put = ff_simple_idct_put_int16_10bit; c->idct_add = ff_simple_idct_add_int16_10bit; c->idct = ff_simple_idct_int16_10bit; } c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->bits_per_raw_sample == 12) { c->idct_put = ff_simple_idct_put_int16_12bit; c->idct_add = ff_simple_idct_add_int16_12bit; c->idct = ff_simple_idct_int16_12bit; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->idct_algo == FF_IDCT_INT) { c->idct_put = ff_jref_idct_put; c->idct_add = ff_jref_idct_add; c->idct = ff_j_rev_dct; c->perm_type = FF_IDCT_PERM_LIBMPEG2; #if CONFIG_FAANIDCT } else if (avctx->idct_algo == FF_IDCT_FAAN) { c->idct_put = ff_faanidct_put; c->idct_add = ff_faanidct_add; c->idct = ff_faanidct; c->perm_type = FF_IDCT_PERM_NONE; #endif /* CONFIG_FAANIDCT */ } else { // accurate/default /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ c->idct_put = ff_simple_idct_put_int16_8bit; c->idct_add = ff_simple_idct_add_int16_8bit; c->idct = ff_simple_idct_int16_8bit; c->perm_type = FF_IDCT_PERM_NONE; } } } c->put_pixels_clamped = ff_put_pixels_clamped_c; c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; c->add_pixels_clamped = ff_add_pixels_clamped_c; if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) ff_xvid_idct_init(c, avctx); if (ARCH_AARCH64) ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); if (ARCH_ALPHA) ff_idctdsp_init_alpha(c, avctx, high_bit_depth); if (ARCH_ARM) ff_idctdsp_init_arm(c, avctx, high_bit_depth); if (ARCH_PPC) ff_idctdsp_init_ppc(c, avctx, high_bit_depth); if (ARCH_X86) ff_idctdsp_init_x86(c, avctx, high_bit_depth); if (ARCH_MIPS) ff_idctdsp_init_mips(c, avctx, high_bit_depth); ff_init_scantable_permutation(c->idct_permutation, c->perm_type); }
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "libavutil/attributes.h" #include "libavutil/common.h" #include "avcodec.h" #include "dct.h" #include "faanidct.h" #include "idctdsp.h" #include "simple_idct.h" #include "xvididct.h" av_cold void ff_init_scantable(uint8_t *permutation, ScanTable *st, const uint8_t *src_scantable) { int i, end; st->scantable = src_scantable; for (i = 0; i < 64; i++) { int j = src_scantable[i]; st->permutated[i] = permutation[j]; } end = -1; for (i = 0; i < 64; i++) { int j = st->permutated[i]; if (j > end) end = j; st->raster_end[i] = end; } } av_cold void ff_init_scantable_permutation(uint8_t *idct_permutation, enum idct_permutation_type perm_type) { int i; if (ARCH_X86) if (ff_init_scantable_permutation_x86(idct_permutation, perm_type)) return; switch (perm_type) { case FF_IDCT_PERM_NONE: for (i = 0; i < 64; i++) idct_permutation[i] = i; break; case FF_IDCT_PERM_LIBMPEG2: for (i = 0; i < 64; i++) idct_permutation[i] = (i & 0x38) | ((i & 6) >> 1) | ((i & 1) << 2); break; case FF_IDCT_PERM_TRANSPOSE: for (i = 0; i < 64; i++) idct_permutation[i] = ((i & 7) << 3) | (i >> 3); break; case FF_IDCT_PERM_PARTTRANS: for (i = 0; i < 64; i++) idct_permutation[i] = (i & 0x24) | ((i & 3) << 3) | ((i >> 3) & 3); break; default: av_log(NULL, AV_LOG_ERROR, "Internal error, IDCT permutation not set\n"); } } void ff_put_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i; /* read the pixels */ for (i = 0; i < 8; i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels[2] = av_clip_uint8(block[2]); pixels[3] = av_clip_uint8(block[3]); pixels[4] = av_clip_uint8(block[4]); pixels[5] = av_clip_uint8(block[5]); pixels[6] = av_clip_uint8(block[6]); pixels[7] = av_clip_uint8(block[7]); pixels += line_size; block += 8; } } static void put_pixels_clamped4_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<4;i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels[2] = av_clip_uint8(block[2]); pixels[3] = av_clip_uint8(block[3]); pixels += line_size; block += 8; } } static void put_pixels_clamped2_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<2;i++) { pixels[0] = av_clip_uint8(block[0]); pixels[1] = av_clip_uint8(block[1]); pixels += line_size; block += 8; } } static void put_signed_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { if (*block < -128) *pixels = 0; else if (*block > 127) *pixels = 255; else *pixels = (uint8_t) (*block + 128); block++; pixels++; } pixels += (line_size - 8); } } void ff_add_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels, ptrdiff_t line_size) { int i; /* read the pixels */ for (i = 0; i < 8; i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels[2] = av_clip_uint8(pixels[2] + block[2]); pixels[3] = av_clip_uint8(pixels[3] + block[3]); pixels[4] = av_clip_uint8(pixels[4] + block[4]); pixels[5] = av_clip_uint8(pixels[5] + block[5]); pixels[6] = av_clip_uint8(pixels[6] + block[6]); pixels[7] = av_clip_uint8(pixels[7] + block[7]); pixels += line_size; block += 8; } } static void add_pixels_clamped4_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<4;i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels[2] = av_clip_uint8(pixels[2] + block[2]); pixels[3] = av_clip_uint8(pixels[3] + block[3]); pixels += line_size; block += 8; } } static void add_pixels_clamped2_c(const int16_t *block, uint8_t *av_restrict pixels, int line_size) { int i; /* read the pixels */ for(i=0;i<2;i++) { pixels[0] = av_clip_uint8(pixels[0] + block[0]); pixels[1] = av_clip_uint8(pixels[1] + block[1]); pixels += line_size; block += 8; } } static void ff_jref_idct4_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct4 (block); put_pixels_clamped4_c(block, dest, line_size); } static void ff_jref_idct4_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct4 (block); add_pixels_clamped4_c(block, dest, line_size); } static void ff_jref_idct2_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct2 (block); put_pixels_clamped2_c(block, dest, line_size); } static void ff_jref_idct2_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { ff_j_rev_dct2 (block); add_pixels_clamped2_c(block, dest, line_size); } static void ff_jref_idct1_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { dest[0] = av_clip_uint8((block[0] + 4)>>3); } static void ff_jref_idct1_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block) { dest[0] = av_clip_uint8(dest[0] + ((block[0] + 4)>>3)); } av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) { const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; if (avctx->lowres==1) { c->idct_put = ff_jref_idct4_put; c->idct_add = ff_jref_idct4_add; c->idct = ff_j_rev_dct4; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==2) { c->idct_put = ff_jref_idct2_put; c->idct_add = ff_jref_idct2_add; c->idct = ff_j_rev_dct2; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==3) { c->idct_put = ff_jref_idct1_put; c->idct_add = ff_jref_idct1_add; c->idct = ff_j_rev_dct1; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT However, it only uses idct_put */ if (c->mpeg4_studio_profile) c->idct_put = ff_simple_idct_put_int32_10bit; else { c->idct_put = ff_simple_idct_put_int16_10bit; c->idct_add = ff_simple_idct_add_int16_10bit; c->idct = ff_simple_idct_int16_10bit; } c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->bits_per_raw_sample == 12) { c->idct_put = ff_simple_idct_put_int16_12bit; c->idct_add = ff_simple_idct_add_int16_12bit; c->idct = ff_simple_idct_int16_12bit; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->idct_algo == FF_IDCT_INT) { c->idct_put = ff_jref_idct_put; c->idct_add = ff_jref_idct_add; c->idct = ff_j_rev_dct; c->perm_type = FF_IDCT_PERM_LIBMPEG2; #if CONFIG_FAANIDCT } else if (avctx->idct_algo == FF_IDCT_FAAN) { c->idct_put = ff_faanidct_put; c->idct_add = ff_faanidct_add; c->idct = ff_faanidct; c->perm_type = FF_IDCT_PERM_NONE; #endif /* CONFIG_FAANIDCT */ } else { // accurate/default /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ c->idct_put = ff_simple_idct_put_int16_8bit; c->idct_add = ff_simple_idct_add_int16_8bit; c->idct = ff_simple_idct_int16_8bit; c->perm_type = FF_IDCT_PERM_NONE; } } } c->put_pixels_clamped = ff_put_pixels_clamped_c; c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; c->add_pixels_clamped = ff_add_pixels_clamped_c; if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) ff_xvid_idct_init(c, avctx); if (ARCH_AARCH64) ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); if (ARCH_ALPHA) ff_idctdsp_init_alpha(c, avctx, high_bit_depth); if (ARCH_ARM) ff_idctdsp_init_arm(c, avctx, high_bit_depth); if (ARCH_PPC) ff_idctdsp_init_ppc(c, avctx, high_bit_depth); if (ARCH_X86) ff_idctdsp_init_x86(c, avctx, high_bit_depth); if (ARCH_MIPS) ff_idctdsp_init_mips(c, avctx, high_bit_depth); ff_init_scantable_permutation(c->idct_permutation, c->perm_type); }
av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) { const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; if (avctx->lowres==1) { c->idct_put = ff_jref_idct4_put; c->idct_add = ff_jref_idct4_add; c->idct = ff_j_rev_dct4; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==2) { c->idct_put = ff_jref_idct2_put; c->idct_add = ff_jref_idct2_add; c->idct = ff_j_rev_dct2; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==3) { c->idct_put = ff_jref_idct1_put; c->idct_add = ff_jref_idct1_add; c->idct = ff_j_rev_dct1; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT However, it only uses idct_put */ if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO) c->idct_put = ff_simple_idct_put_int32_10bit; else { c->idct_put = ff_simple_idct_put_int16_10bit; c->idct_add = ff_simple_idct_add_int16_10bit; c->idct = ff_simple_idct_int16_10bit; } c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->bits_per_raw_sample == 12) { c->idct_put = ff_simple_idct_put_int16_12bit; c->idct_add = ff_simple_idct_add_int16_12bit; c->idct = ff_simple_idct_int16_12bit; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->idct_algo == FF_IDCT_INT) { c->idct_put = ff_jref_idct_put; c->idct_add = ff_jref_idct_add; c->idct = ff_j_rev_dct; c->perm_type = FF_IDCT_PERM_LIBMPEG2; #if CONFIG_FAANIDCT } else if (avctx->idct_algo == FF_IDCT_FAAN) { c->idct_put = ff_faanidct_put; c->idct_add = ff_faanidct_add; c->idct = ff_faanidct; c->perm_type = FF_IDCT_PERM_NONE; #endif /* CONFIG_FAANIDCT */ } else { // accurate/default /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ c->idct_put = ff_simple_idct_put_int16_8bit; c->idct_add = ff_simple_idct_add_int16_8bit; c->idct = ff_simple_idct_int16_8bit; c->perm_type = FF_IDCT_PERM_NONE; } } } c->put_pixels_clamped = ff_put_pixels_clamped_c; c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; c->add_pixels_clamped = ff_add_pixels_clamped_c; if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) ff_xvid_idct_init(c, avctx); if (ARCH_AARCH64) ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); if (ARCH_ALPHA) ff_idctdsp_init_alpha(c, avctx, high_bit_depth); if (ARCH_ARM) ff_idctdsp_init_arm(c, avctx, high_bit_depth); if (ARCH_PPC) ff_idctdsp_init_ppc(c, avctx, high_bit_depth); if (ARCH_X86) ff_idctdsp_init_x86(c, avctx, high_bit_depth); if (ARCH_MIPS) ff_idctdsp_init_mips(c, avctx, high_bit_depth); ff_init_scantable_permutation(c->idct_permutation, c->perm_type); }
av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) { const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; if (avctx->lowres==1) { c->idct_put = ff_jref_idct4_put; c->idct_add = ff_jref_idct4_add; c->idct = ff_j_rev_dct4; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==2) { c->idct_put = ff_jref_idct2_put; c->idct_add = ff_jref_idct2_add; c->idct = ff_j_rev_dct2; c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->lowres==3) { c->idct_put = ff_jref_idct1_put; c->idct_add = ff_jref_idct1_add; c->idct = ff_j_rev_dct1; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT However, it only uses idct_put */ if (c->mpeg4_studio_profile) c->idct_put = ff_simple_idct_put_int32_10bit; else { c->idct_put = ff_simple_idct_put_int16_10bit; c->idct_add = ff_simple_idct_add_int16_10bit; c->idct = ff_simple_idct_int16_10bit; } c->perm_type = FF_IDCT_PERM_NONE; } else if (avctx->bits_per_raw_sample == 12) { c->idct_put = ff_simple_idct_put_int16_12bit; c->idct_add = ff_simple_idct_add_int16_12bit; c->idct = ff_simple_idct_int16_12bit; c->perm_type = FF_IDCT_PERM_NONE; } else { if (avctx->idct_algo == FF_IDCT_INT) { c->idct_put = ff_jref_idct_put; c->idct_add = ff_jref_idct_add; c->idct = ff_j_rev_dct; c->perm_type = FF_IDCT_PERM_LIBMPEG2; #if CONFIG_FAANIDCT } else if (avctx->idct_algo == FF_IDCT_FAAN) { c->idct_put = ff_faanidct_put; c->idct_add = ff_faanidct_add; c->idct = ff_faanidct; c->perm_type = FF_IDCT_PERM_NONE; #endif /* CONFIG_FAANIDCT */ } else { // accurate/default /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ c->idct_put = ff_simple_idct_put_int16_8bit; c->idct_add = ff_simple_idct_add_int16_8bit; c->idct = ff_simple_idct_int16_8bit; c->perm_type = FF_IDCT_PERM_NONE; } } } c->put_pixels_clamped = ff_put_pixels_clamped_c; c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; c->add_pixels_clamped = ff_add_pixels_clamped_c; if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) ff_xvid_idct_init(c, avctx); if (ARCH_AARCH64) ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); if (ARCH_ALPHA) ff_idctdsp_init_alpha(c, avctx, high_bit_depth); if (ARCH_ARM) ff_idctdsp_init_arm(c, avctx, high_bit_depth); if (ARCH_PPC) ff_idctdsp_init_ppc(c, avctx, high_bit_depth); if (ARCH_X86) ff_idctdsp_init_x86(c, avctx, high_bit_depth); if (ARCH_MIPS) ff_idctdsp_init_mips(c, avctx, high_bit_depth); ff_init_scantable_permutation(c->idct_permutation, c->perm_type); }
{'added': [(261, ' if (c->mpeg4_studio_profile)')], 'deleted': [(261, ' if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO)')]}
1
1
257
1,808
https://github.com/FFmpeg/FFmpeg
CVE-2018-12460
['CWE-476']
rdp.c
rdp_read_flow_control_pdu
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.rdp") const char* DATA_PDU_TYPE_STRINGS[80] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout", /* 0x37 */ "FrameAcknowledge", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; static void rdp_read_flow_control_pdu(wStream* s, UINT16* type); static void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id); static void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id); /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(wStream* s, UINT16* flags, UINT16* length) { /* Basic Security Header */ if ((Stream_GetRemainingLength(s) < 4) || (length && (*length < 4))) return FALSE; Stream_Read_UINT16(s, *flags); /* flags */ Stream_Seek(s, 2); /* flagsHi (unused) */ if (length) *length -= 4; return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(wStream* s, UINT16 flags) { /* Basic Security Header */ Stream_Write_UINT16(s, flags); /* flags */ Stream_Write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, *length); /* totalLength */ /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (*length == 0x8000) { rdp_read_flow_control_pdu(s, type); *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if (((size_t)*length - 2) > Stream_GetRemainingLength(s)) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (*length > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ Stream_Write_UINT16(s, length); /* totalLength */ Stream_Write_UINT16(s, type | 0x10); /* pduType */ Stream_Write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(wStream* s, UINT16* length, BYTE* type, UINT32* shareId, BYTE* compressedType, UINT16* compressedLength) { if (Stream_GetRemainingLength(s) < 12) return FALSE; /* Share Data Header */ Stream_Read_UINT32(s, *shareId); /* shareId (4 bytes) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT8(s); /* streamId (1 byte) */ Stream_Read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ Stream_Read_UINT8(s, *type); /* pduType2, Data PDU Type (1 byte) */ Stream_Read_UINT8(s, *compressedType); /* compressedType (1 byte) */ Stream_Read_UINT16(s, *compressedLength); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ Stream_Write_UINT32(s, share_id); /* shareId (4 bytes) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT8(s, STREAM_LOW); /* streamId (1 byte) */ Stream_Write_UINT16(s, length); /* uncompressedLength (2 bytes) */ Stream_Write_UINT8(s, type); /* pduType2, Data PDU Type (1 byte) */ Stream_Write_UINT8(s, 0); /* compressedType (1 byte) */ Stream_Write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static BOOL rdp_security_stream_init(rdpRdp* rdp, wStream* s, BOOL sec_header) { if (!rdp || !s) return FALSE; if (rdp->do_crypt) { if (!Stream_SafeSeek(s, 12)) return FALSE; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { if (!Stream_SafeSeek(s, 4)) return FALSE; } rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0 || sec_header) { if (!Stream_SafeSeek(s, 4)) return FALSE; } return TRUE; } wStream* rdp_send_stream_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, FALSE)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_send_stream_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_CONTROL_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_data_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_DATA_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } BOOL rdp_set_error_info(rdpRdp* rdp, UINT32 errorInfo) { rdp->errorInfo = errorInfo; if (rdp->errorInfo != ERRINFO_SUCCESS) { rdpContext* context = rdp->context; rdp_print_errinfo(rdp->errorInfo); if (context) { freerdp_set_last_error_log(context, MAKE_FREERDP_ERROR(ERRINFO, errorInfo)); if (context->pubSub) { ErrorInfoEventArgs e; EventArgsInit(&e, "freerdp"); e.code = rdp->errorInfo; PubSub_OnErrorInfo(context->pubSub, context, &e); } } else WLog_ERR(TAG, "%s missing context=%p", __FUNCTION__, context); } else { freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SUCCESS); } return TRUE; } wStream* rdp_message_channel_pdu_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, TRUE)) goto fail; return s; fail: Stream_Release(s); return NULL; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, wStream* s, UINT16* length, UINT16* channelId) { BYTE li; BYTE byte; BYTE code; BYTE choice; UINT16 initiator; enum DomainMCSPDU MCSPDU; enum DomainMCSPDU domainMCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!tpkt_read_header(s, length)) return FALSE; if (!tpdu_read_header(s, &code, &li, *length)) return FALSE; if (code != X224_TPDU_DATA) { if (code == X224_TPDU_DISCONNECT_REQUEST) { freerdp_abort_connect(rdp->instance); return TRUE; } return FALSE; } if (!per_read_choice(s, &choice)) return FALSE; domainMCSPDU = (enum DomainMCSPDU)(choice >> 2); if (domainMCSPDU != MCSPDU) { if (domainMCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } MCSPDU = domainMCSPDU; if (*length < 8U) return FALSE; if ((*length - 8U) > Stream_GetRemainingLength(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { int reason = 0; TerminateEventArgs e; rdpContext* context; if (!mcs_recv_disconnect_provider_ultimatum(rdp->mcs, s, &reason)) return FALSE; if (!rdp->instance) return FALSE; context = rdp->instance->context; context->disconnectUltimatum = reason; if (rdp->errorInfo == ERRINFO_SUCCESS) { /** * Some servers like Windows Server 2008 R2 do not send the error info pdu * when the user logs off like they should. Map DisconnectProviderUltimatum * to a ERRINFO_LOGOFF_BY_USER when the errinfo code is ERRINFO_SUCCESS. */ if (reason == Disconnect_Ultimatum_provider_initiated) rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); else if (reason == Disconnect_Ultimatum_user_requested) rdp_set_error_info(rdp, ERRINFO_LOGOFF_BY_USER); else rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); } WLog_DBG(TAG, "DisconnectProviderUltimatum: reason: %d", reason); freerdp_abort_connect(rdp->instance); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); return TRUE; } if (Stream_GetRemainingLength(s) < 5) return FALSE; if (!per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID)) /* initiator (UserId) */ return FALSE; if (!per_read_integer16(s, channelId, 0)) /* channelId */ return FALSE; Stream_Read_UINT8(s, byte); /* dataPriority + Segmentation (0x70) */ if (!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > Stream_GetRemainingLength(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, wStream* s, UINT16 length, UINT16 channelId) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->userId, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channelId, 0); /* channelId */ Stream_Write_UINT8(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, even though we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; Stream_Write_UINT16_BE(s, length); /* userData (OCTET_STRING) */ } static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, int length, UINT32 sec_flags, UINT32* pad) { BYTE* data; BOOL status; sec_flags |= rdp->sec_flags; *pad = 0; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = Stream_Pointer(s) + 12; length = length - (data - Stream_Buffer(s)); Stream_Write_UINT16(s, 0x10); /* length */ Stream_Write_UINT8(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ *pad = 8 - (length % 8); if (*pad == 8) *pad = 0; if (*pad) memset(data + length, 0, *pad); Stream_Write_UINT8(s, *pad); if (!security_hmac_signature(data, length, Stream_Pointer(s), rdp)) return FALSE; Stream_Seek(s, 8); security_fips_encrypt(data, length + *pad, rdp); } else { data = Stream_Pointer(s) + 8; length = length - (data - Stream_Buffer(s)); if (sec_flags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, data, length, TRUE, Stream_Pointer(s)); else status = security_mac_signature(rdp, data, length, Stream_Pointer(s)); if (!status) return FALSE; Stream_Seek(s, 8); if (!security_encrypt(Stream_Pointer(s), length, rdp)) return FALSE; } } rdp->sec_flags = 0; } return TRUE; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp, UINT16 sec_flags) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0 || sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet. * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, wStream* s, UINT16 channel_id) { BOOL rc = FALSE; UINT32 pad; UINT16 length; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, channel_id); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_pdu(rdpRdp* rdp, wStream* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!rdp || !s) return FALSE; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) return FALSE; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, wStream* s, BYTE type, UINT16 channel_id) { BOOL rc = FALSE; size_t length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); WLog_DBG(TAG, "%s: sending data (type=0x%x size=%" PRIuz " channelId=%" PRIu16 ")", __FUNCTION__, type, Stream_Length(s), channel_id); rdp->outPackets++; if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags) { BOOL rc = FALSE; UINT16 length; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId); if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } static BOOL rdp_recv_server_shutdown_denied_pdu(rdpRdp* rdp, wStream* s) { return TRUE; } static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT16 ledFlags; rdpContext* context = rdp->instance->context; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */ IFCALL(context->update->SetKeyboardIndicators, context, ledFlags); return TRUE; } static BOOL rdp_recv_server_set_keyboard_ime_status_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT32 imeState; UINT32 imeConvMode; if (!rdp || !rdp->input) return FALSE; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT32(s, imeState); /* imeState (4 bytes) */ Stream_Read_UINT32(s, imeConvMode); /* imeConvMode (4 bytes) */ IFCALL(rdp->update->SetKeyboardImeStatus, rdp->context, unitId, imeState, imeConvMode); return TRUE; } static BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, wStream* s) { UINT32 errorInfo; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, errorInfo); /* errorInfo (4 bytes) */ return rdp_set_error_info(rdp, errorInfo); } static BOOL rdp_recv_server_auto_reconnect_status_pdu(rdpRdp* rdp, wStream* s) { UINT32 arcStatus; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, arcStatus); /* arcStatus (4 bytes) */ WLog_WARN(TAG, "AutoReconnectStatus: 0x%08" PRIX32 "", arcStatus); return TRUE; } static BOOL rdp_recv_server_status_info_pdu(rdpRdp* rdp, wStream* s) { UINT32 statusCode; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, statusCode); /* statusCode (4 bytes) */ if (rdp->update->ServerStatusInfo) return rdp->update->ServerStatusInfo(rdp->context, statusCode); return TRUE; } static BOOL rdp_recv_monitor_layout_pdu(rdpRdp* rdp, wStream* s) { UINT32 index; UINT32 monitorCount; MONITOR_DEF* monitor; MONITOR_DEF* monitorDefArray; BOOL ret = TRUE; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, monitorCount); /* monitorCount (4 bytes) */ if ((Stream_GetRemainingLength(s) / 20) < monitorCount) return FALSE; monitorDefArray = (MONITOR_DEF*)calloc(monitorCount, sizeof(MONITOR_DEF)); if (!monitorDefArray) return FALSE; for (monitor = monitorDefArray, index = 0; index < monitorCount; index++, monitor++) { Stream_Read_UINT32(s, monitor->left); /* left (4 bytes) */ Stream_Read_UINT32(s, monitor->top); /* top (4 bytes) */ Stream_Read_UINT32(s, monitor->right); /* right (4 bytes) */ Stream_Read_UINT32(s, monitor->bottom); /* bottom (4 bytes) */ Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */ } IFCALLRET(rdp->update->RemoteMonitors, ret, rdp->context, monitorCount, monitorDefArray); free(monitorDefArray); return ret; } int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { BYTE type; wStream* cs; UINT16 length; UINT32 shareId; BYTE compressedType; UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) { WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; } cs = s; if (compressedType & PACKET_COMPRESSED) { UINT32 DstSize = 0; BYTE* pDstData = NULL; UINT16 SrcSize = compressedLength - 18; if ((compressedLength < 18) || (Stream_GetRemainingLength(s) < SrcSize)) { WLog_ERR(TAG, "bulk_decompress: not enough bytes for compressedLength %" PRIu16 "", compressedLength); return -1; } if (bulk_decompress(rdp->bulk, Stream_Pointer(s), SrcSize, &pDstData, &DstSize, compressedType)) { if (!(cs = StreamPool_Take(rdp->transport->ReceivePool, DstSize))) { WLog_ERR(TAG, "Couldn't take stream from pool"); return -1; } Stream_SetPosition(cs, 0); Stream_Write(cs, pDstData, DstSize); Stream_SealLength(cs); Stream_SetPosition(cs, 0); } else { WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } Stream_Seek(s, SrcSize); } WLog_DBG(TAG, "recv %s Data PDU (0x%02" PRIX8 "), length: %" PRIu16 "", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - " "rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - " "rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - " "rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; } break; default: break; } if (cs != s) Stream_Release(cs); return 0; out_fail: if (cs != s) Stream_Release(cs); return -1; } int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ return rdp_recv_autodetect_request_packet(rdp, s); } if (securityFlags & SEC_AUTODETECT_RSP) { /* Client Auto-Detect Response PDU */ return rdp_recv_autodetect_response_packet(rdp, s); } if (securityFlags & SEC_HEARTBEAT) { /* Heartbeat PDU */ return rdp_recv_heartbeat_packet(rdp, s); } if (securityFlags & SEC_TRANSPORT_REQ) { /* Initiate Multitransport Request PDU */ return rdp_recv_multitransport_packet(rdp, s); } return -1; } int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return -1; if (type == PDU_TYPE_DATA) { return rdp_recv_data_pdu(rdp, s); } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else if (type == PDU_TYPE_FLOW_RESPONSE || type == PDU_TYPE_FLOW_STOP || type == PDU_TYPE_FLOW_TEST) { return 0; } else { return -1; } } void rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, wStream* s, UINT16* pLength, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; BOOL status; INT32 length; if (!rdp || !s || !pLength) return FALSE; length = *pLength; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; INT64 padLength; if (Stream_GetRemainingLength(s) < 12) return FALSE; Stream_Read_UINT16(s, len); /* 0x10 */ Stream_Read_UINT8(s, version); /* 0x1 */ Stream_Read_UINT8(s, pad); sig = Stream_Pointer(s); Stream_Seek(s, 8); /* signature */ length -= 12; padLength = length - pad; if ((length <= 0) || (padLength <= 0)) return FALSE; if (!security_fips_decrypt(Stream_Pointer(s), length, rdp)) { WLog_ERR(TAG, "FATAL: cannot decrypt"); return FALSE; /* TODO */ } if (!security_fips_check_signature(Stream_Pointer(s), length - pad, sig, rdp)) { WLog_ERR(TAG, "FATAL: invalid packet signature"); return FALSE; /* TODO */ } Stream_SetLength(s, Stream_Length(s) - pad); *pLength = padLength; return TRUE; } if (Stream_GetRemainingLength(s) < sizeof(wmac)) return FALSE; Stream_Read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (length <= 0) return FALSE; if (!security_decrypt(Stream_Pointer(s), length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, Stream_Pointer(s), length, FALSE, cmac); else status = security_mac_signature(rdp, Stream_Pointer(s), length, cmac); if (!status) return FALSE; if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { WLog_ERR(TAG, "WARNING: invalid packet signature"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ // return FALSE; } *pLength = length; return TRUE; } static const char* pdu_type_to_str(UINT16 pduType) { static char buffer[1024] = { 0 }; switch (pduType) { case PDU_TYPE_DEMAND_ACTIVE: return "PDU_TYPE_DEMAND_ACTIVE"; case PDU_TYPE_CONFIRM_ACTIVE: return "PDU_TYPE_CONFIRM_ACTIVE"; case PDU_TYPE_DEACTIVATE_ALL: return "PDU_TYPE_DEACTIVATE_ALL"; case PDU_TYPE_DATA: return "PDU_TYPE_DATA"; case PDU_TYPE_SERVER_REDIRECTION: return "PDU_TYPE_SERVER_REDIRECTION"; case PDU_TYPE_FLOW_TEST: return "PDU_TYPE_FLOW_TEST"; case PDU_TYPE_FLOW_RESPONSE: return "PDU_TYPE_FLOW_RESPONSE"; case PDU_TYPE_FLOW_STOP: return "PDU_TYPE_FLOW_STOP"; default: _snprintf(buffer, sizeof(buffer), "UNKNOWN %04" PRIx16, pduType); return buffer; } } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) { int rc = 0; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId = 0; UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, &length, &channelId)) { WLog_ERR(TAG, "Incorrect RDP header."); return -1; } if (freerdp_shall_disconnect(rdp->instance)) return 0; if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, &length)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, &length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ Stream_Rewind(s, 2); rdp->inPackets++; rc = rdp_recv_enhanced_security_redirection_packet(rdp, s); goto out; } } if (channelId == MCS_GLOBAL_CHANNEL_ID) { while (Stream_GetRemainingLength(s) > 3) { size_t startheader, endheader, start, end, diff, headerdiff; startheader = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; } start = endheader = Stream_GetPosition(s); headerdiff = endheader - startheader; if (pduLength < headerdiff) { WLog_ERR( TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() invalid pduLength %" PRIu16, pduLength); return -1; } pduLength -= headerdiff; rdp->settings->PduSource = pduSource; rdp->inPackets++; switch (pduType) { case PDU_TYPE_DATA: rc = rdp_recv_data_pdu(rdp, s); if (rc < 0) return rc; break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; } break; case PDU_TYPE_SERVER_REDIRECTION: return rdp_recv_enhanced_security_redirection_packet(rdp, s); case PDU_TYPE_FLOW_RESPONSE: case PDU_TYPE_FLOW_STOP: case PDU_TYPE_FLOW_TEST: WLog_DBG(TAG, "flow message 0x%04" PRIX16 "", pduType); /* http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (!Stream_SafeSeek(s, pduLength)) return -1; break; default: WLog_ERR(TAG, "incorrect PDU type: 0x%04" PRIX16 "", pduType); break; } end = Stream_GetPosition(s); diff = end - start; if (diff != pduLength) { WLog_WARN(TAG, "pduType %s not properly parsed, %" PRIdz " bytes remaining unhandled. Skipping.", pdu_type_to_str(pduType), diff); if (!Stream_SafeSeek(s, pduLength)) return -1; } } } else if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId)) { if (!rdp->settings->UseRdpSecurityLayer) if (!rdp_read_security_header(s, &securityFlags, NULL)) return -1; rdp->inPackets++; rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { rdp->inPackets++; if (!freerdp_channel_process(rdp->instance, s, channelId, length)) return -1; } out: if (!tpkt_ensure_stream_consumed(s, length)) return -1; return rc; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { WLog_ERR(TAG, "incorrect FastPath PDU header length %" PRIu16 "", length); return -1; } if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, &length, flags)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; } } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, wStream* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*)extra; /* * At any point in the connection sequence between when all * MCS channels have been joined and when the RDP connection * enters the active state, an auto-detect PDU can be received * on the MCS message channel. */ if ((rdp->state > CONNECTION_STATE_MCS_CHANNEL_JOIN) && (rdp->state < CONNECTION_STATE_ACTIVE)) { if (rdp_client_connect_auto_detect(rdp, s)) return 0; } switch (rdp->state) { case CONNECTION_STATE_NLA: if (nla_get_state(rdp->nla) < NLA_STATE_AUTH_INFO) { if (nla_recv_pdu(rdp->nla, s) < 1) { WLog_ERR(TAG, "%s: %s - nla_recv_pdu() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } else if (nla_get_state(rdp->nla) == NLA_STATE_POST_NEGO) { nego_recv(rdp->transport, s, (void*)rdp->nego); if (nego_get_state(rdp->nego) != NEGO_STATE_FINAL) { WLog_ERR(TAG, "%s: %s - nego_recv() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } if (nla_get_state(rdp->nla) == NLA_STATE_AUTH_INFO) { transport_set_nla_mode(rdp->transport, FALSE); if (rdp->settings->VmConnectMode) { if (!nego_set_state(rdp->nego, NEGO_STATE_NLA)) return -1; if (!nego_set_requested_protocols(rdp->nego, PROTOCOL_HYBRID | PROTOCOL_SSL)) return -1; nego_send_negotiation_request(rdp->nego); if (!nla_set_state(rdp->nla, NLA_STATE_POST_NEGO)) return -1; } else { if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } } if (nla_get_state(rdp->nla) == NLA_STATE_FINAL) { nla_free(rdp->nla); rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) { WLog_ERR(TAG, "%s: %s - mcs_client_begin() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } break; case CONNECTION_STATE_MCS_CONNECT: if (!mcs_recv_connect_response(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_connect_response failure"); return -1; } if (!mcs_send_erect_domain_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_erect_domain_request failure"); return -1; } if (!mcs_send_attach_user_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_attach_user_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER); break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!mcs_recv_attach_user_confirm(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_attach_user_confirm failure"); return -1; } if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->userId)) { WLog_ERR(TAG, "mcs_send_channel_join_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN); break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) { WLog_ERR(TAG, "%s: %s - " "rdp_client_connect_mcs_channel_join_confirm() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); status = -1; } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_client_connect_license() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - " "rdp_client_connect_demand_active() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) { ActivatedEventArgs activatedEvent; rdpContext* context = rdp->context; rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); EventArgsInit(&activatedEvent, "libfreerdp"); activatedEvent.firstActivation = !rdp->deactivation_reactivation; PubSub_OnActivated(context->pubSub, context, &activatedEvent); return 2; } if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; default: WLog_ERR(TAG, "%s: %s state %d", __FUNCTION__, rdp_server_connection_state_string(rdp->state), rdp->state); status = -1; break; } return status; } BOOL rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, const BYTE* data, size_t size) { return freerdp_channel_send(rdp, channelId, data, size); } BOOL rdp_send_error_info(rdpRdp* rdp) { wStream* s; BOOL status; if (rdp->errorInfo == ERRINFO_SUCCESS) return TRUE; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, rdp->errorInfo); /* error id (4 bytes) */ status = rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_ERROR_INFO, 0); return status; } int rdp_check_fds(rdpRdp* rdp) { int status; rdpTransport* transport = rdp->transport; if (transport->tsg) { rdpTsg* tsg = transport->tsg; if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles()"); return -1; } if (tsg_get_state(tsg) != TSG_STATE_PIPE_CREATED) return 1; } status = transport_check_fds(transport); if (status == 1) { if (!rdp_client_redirect(rdp)) /* session redirection */ return -1; } if (status < 0) WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } BOOL freerdp_get_stats(rdpRdp* rdp, UINT64* inBytes, UINT64* outBytes, UINT64* inPackets, UINT64* outPackets) { if (!rdp) return FALSE; if (inBytes) *inBytes = rdp->inBytes; if (outBytes) *outBytes = rdp->outBytes; if (inPackets) *inPackets = rdp->inPackets; if (outPackets) *outPackets = rdp->outPackets; return TRUE; } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(rdpContext* context) { rdpRdp* rdp; DWORD flags; BOOL newSettings = FALSE; rdp = (rdpRdp*)calloc(1, sizeof(rdpRdp)); if (!rdp) return NULL; rdp->context = context; rdp->instance = context->instance; flags = 0; if (context->ServerMode) flags |= FREERDP_SETTINGS_SERVER_MODE; if (!context->settings) { context->settings = freerdp_settings_new(flags); if (!context->settings) goto out_free; newSettings = TRUE; } rdp->settings = context->settings; if (context->instance) { rdp->settings->instance = context->instance; context->instance->settings = rdp->settings; } else if (context->peer) { rdp->settings->instance = context->peer; context->peer->settings = rdp->settings; } rdp->transport = transport_new(context); if (!rdp->transport) goto out_free_settings; rdp->license = license_new(rdp); if (!rdp->license) goto out_free_transport; rdp->input = input_new(rdp); if (!rdp->input) goto out_free_license; rdp->update = update_new(rdp); if (!rdp->update) goto out_free_input; rdp->fastpath = fastpath_new(rdp); if (!rdp->fastpath) goto out_free_update; rdp->nego = nego_new(rdp->transport); if (!rdp->nego) goto out_free_fastpath; rdp->mcs = mcs_new(rdp->transport); if (!rdp->mcs) goto out_free_nego; rdp->redirection = redirection_new(); if (!rdp->redirection) goto out_free_mcs; rdp->autodetect = autodetect_new(); if (!rdp->autodetect) goto out_free_redirection; rdp->heartbeat = heartbeat_new(); if (!rdp->heartbeat) goto out_free_autodetect; rdp->multitransport = multitransport_new(); if (!rdp->multitransport) goto out_free_heartbeat; rdp->bulk = bulk_new(context); if (!rdp->bulk) goto out_free_multitransport; return rdp; out_free_multitransport: multitransport_free(rdp->multitransport); out_free_heartbeat: heartbeat_free(rdp->heartbeat); out_free_autodetect: autodetect_free(rdp->autodetect); out_free_redirection: redirection_free(rdp->redirection); out_free_mcs: mcs_free(rdp->mcs); out_free_nego: nego_free(rdp->nego); out_free_fastpath: fastpath_free(rdp->fastpath); out_free_update: update_free(rdp->update); out_free_input: input_free(rdp->input); out_free_license: license_free(rdp->license); out_free_transport: transport_free(rdp->transport); out_free_settings: if (newSettings) freerdp_settings_free(rdp->settings); out_free: free(rdp); return NULL; } void rdp_reset(rdpRdp* rdp) { rdpContext* context; rdpSettings* settings; context = rdp->context; settings = rdp->settings; bulk_reset(rdp->bulk); if (rdp->rc4_decrypt_key) { winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = NULL; } if (rdp->rc4_encrypt_key) { winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = NULL; } if (rdp->fips_encrypt) { winpr_Cipher_Free(rdp->fips_encrypt); rdp->fips_encrypt = NULL; } if (rdp->fips_decrypt) { winpr_Cipher_Free(rdp->fips_decrypt); rdp->fips_decrypt = NULL; } if (settings->ServerRandom) { free(settings->ServerRandom); settings->ServerRandom = NULL; settings->ServerRandomLength = 0; } if (settings->ServerCertificate) { free(settings->ServerCertificate); settings->ServerCertificate = NULL; } if (settings->ClientAddress) { free(settings->ClientAddress); settings->ClientAddress = NULL; } mcs_free(rdp->mcs); nego_free(rdp->nego); license_free(rdp->license); transport_free(rdp->transport); fastpath_free(rdp->fastpath); rdp->transport = transport_new(context); rdp->license = license_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->fastpath = fastpath_new(rdp); rdp->transport->layer = TRANSPORT_LAYER_TCP; rdp->errorInfo = 0; rdp->deactivation_reactivation = 0; rdp->finalize_sc_pdus = 0; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp) { winpr_RC4_Free(rdp->rc4_decrypt_key); winpr_RC4_Free(rdp->rc4_encrypt_key); winpr_Cipher_Free(rdp->fips_encrypt); winpr_Cipher_Free(rdp->fips_decrypt); freerdp_settings_free(rdp->settings); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); nla_free(rdp->nla); redirection_free(rdp->redirection); autodetect_free(rdp->autodetect); heartbeat_free(rdp->heartbeat); multitransport_free(rdp->multitransport); bulk_free(rdp->bulk); free(rdp); } }
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.rdp") const char* DATA_PDU_TYPE_STRINGS[80] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout", /* 0x37 */ "FrameAcknowledge", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; static BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type); static void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id); static void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id); /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(wStream* s, UINT16* flags, UINT16* length) { /* Basic Security Header */ if ((Stream_GetRemainingLength(s) < 4) || (length && (*length < 4))) return FALSE; Stream_Read_UINT16(s, *flags); /* flags */ Stream_Seek(s, 2); /* flagsHi (unused) */ if (length) *length -= 4; return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(wStream* s, UINT16 flags) { /* Basic Security Header */ Stream_Write_UINT16(s, flags); /* flags */ Stream_Write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { UINT16 len; if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, len); /* totalLength */ *length = len; /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (len == 0x8000) { if (!rdp_read_flow_control_pdu(s, type)) return FALSE; *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s))) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (len > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ Stream_Write_UINT16(s, length); /* totalLength */ Stream_Write_UINT16(s, type | 0x10); /* pduType */ Stream_Write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(wStream* s, UINT16* length, BYTE* type, UINT32* shareId, BYTE* compressedType, UINT16* compressedLength) { if (Stream_GetRemainingLength(s) < 12) return FALSE; /* Share Data Header */ Stream_Read_UINT32(s, *shareId); /* shareId (4 bytes) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT8(s); /* streamId (1 byte) */ Stream_Read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ Stream_Read_UINT8(s, *type); /* pduType2, Data PDU Type (1 byte) */ Stream_Read_UINT8(s, *compressedType); /* compressedType (1 byte) */ Stream_Read_UINT16(s, *compressedLength); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ Stream_Write_UINT32(s, share_id); /* shareId (4 bytes) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT8(s, STREAM_LOW); /* streamId (1 byte) */ Stream_Write_UINT16(s, length); /* uncompressedLength (2 bytes) */ Stream_Write_UINT8(s, type); /* pduType2, Data PDU Type (1 byte) */ Stream_Write_UINT8(s, 0); /* compressedType (1 byte) */ Stream_Write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static BOOL rdp_security_stream_init(rdpRdp* rdp, wStream* s, BOOL sec_header) { if (!rdp || !s) return FALSE; if (rdp->do_crypt) { if (!Stream_SafeSeek(s, 12)) return FALSE; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { if (!Stream_SafeSeek(s, 4)) return FALSE; } rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0 || sec_header) { if (!Stream_SafeSeek(s, 4)) return FALSE; } return TRUE; } wStream* rdp_send_stream_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, FALSE)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_send_stream_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_CONTROL_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_data_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_DATA_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } BOOL rdp_set_error_info(rdpRdp* rdp, UINT32 errorInfo) { rdp->errorInfo = errorInfo; if (rdp->errorInfo != ERRINFO_SUCCESS) { rdpContext* context = rdp->context; rdp_print_errinfo(rdp->errorInfo); if (context) { freerdp_set_last_error_log(context, MAKE_FREERDP_ERROR(ERRINFO, errorInfo)); if (context->pubSub) { ErrorInfoEventArgs e; EventArgsInit(&e, "freerdp"); e.code = rdp->errorInfo; PubSub_OnErrorInfo(context->pubSub, context, &e); } } else WLog_ERR(TAG, "%s missing context=%p", __FUNCTION__, context); } else { freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SUCCESS); } return TRUE; } wStream* rdp_message_channel_pdu_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, TRUE)) goto fail; return s; fail: Stream_Release(s); return NULL; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, wStream* s, UINT16* length, UINT16* channelId) { BYTE li; BYTE byte; BYTE code; BYTE choice; UINT16 initiator; enum DomainMCSPDU MCSPDU; enum DomainMCSPDU domainMCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!tpkt_read_header(s, length)) return FALSE; if (!tpdu_read_header(s, &code, &li, *length)) return FALSE; if (code != X224_TPDU_DATA) { if (code == X224_TPDU_DISCONNECT_REQUEST) { freerdp_abort_connect(rdp->instance); return TRUE; } return FALSE; } if (!per_read_choice(s, &choice)) return FALSE; domainMCSPDU = (enum DomainMCSPDU)(choice >> 2); if (domainMCSPDU != MCSPDU) { if (domainMCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } MCSPDU = domainMCSPDU; if (*length < 8U) return FALSE; if ((*length - 8U) > Stream_GetRemainingLength(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { int reason = 0; TerminateEventArgs e; rdpContext* context; if (!mcs_recv_disconnect_provider_ultimatum(rdp->mcs, s, &reason)) return FALSE; if (!rdp->instance) return FALSE; context = rdp->instance->context; context->disconnectUltimatum = reason; if (rdp->errorInfo == ERRINFO_SUCCESS) { /** * Some servers like Windows Server 2008 R2 do not send the error info pdu * when the user logs off like they should. Map DisconnectProviderUltimatum * to a ERRINFO_LOGOFF_BY_USER when the errinfo code is ERRINFO_SUCCESS. */ if (reason == Disconnect_Ultimatum_provider_initiated) rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); else if (reason == Disconnect_Ultimatum_user_requested) rdp_set_error_info(rdp, ERRINFO_LOGOFF_BY_USER); else rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); } WLog_DBG(TAG, "DisconnectProviderUltimatum: reason: %d", reason); freerdp_abort_connect(rdp->instance); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); return TRUE; } if (Stream_GetRemainingLength(s) < 5) return FALSE; if (!per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID)) /* initiator (UserId) */ return FALSE; if (!per_read_integer16(s, channelId, 0)) /* channelId */ return FALSE; Stream_Read_UINT8(s, byte); /* dataPriority + Segmentation (0x70) */ if (!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > Stream_GetRemainingLength(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, wStream* s, UINT16 length, UINT16 channelId) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->userId, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channelId, 0); /* channelId */ Stream_Write_UINT8(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, even though we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; Stream_Write_UINT16_BE(s, length); /* userData (OCTET_STRING) */ } static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, int length, UINT32 sec_flags, UINT32* pad) { BYTE* data; BOOL status; sec_flags |= rdp->sec_flags; *pad = 0; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = Stream_Pointer(s) + 12; length = length - (data - Stream_Buffer(s)); Stream_Write_UINT16(s, 0x10); /* length */ Stream_Write_UINT8(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ *pad = 8 - (length % 8); if (*pad == 8) *pad = 0; if (*pad) memset(data + length, 0, *pad); Stream_Write_UINT8(s, *pad); if (!security_hmac_signature(data, length, Stream_Pointer(s), rdp)) return FALSE; Stream_Seek(s, 8); security_fips_encrypt(data, length + *pad, rdp); } else { data = Stream_Pointer(s) + 8; length = length - (data - Stream_Buffer(s)); if (sec_flags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, data, length, TRUE, Stream_Pointer(s)); else status = security_mac_signature(rdp, data, length, Stream_Pointer(s)); if (!status) return FALSE; Stream_Seek(s, 8); if (!security_encrypt(Stream_Pointer(s), length, rdp)) return FALSE; } } rdp->sec_flags = 0; } return TRUE; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp, UINT16 sec_flags) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0 || sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet. * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, wStream* s, UINT16 channel_id) { BOOL rc = FALSE; UINT32 pad; UINT16 length; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, channel_id); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_pdu(rdpRdp* rdp, wStream* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!rdp || !s) return FALSE; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) return FALSE; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, wStream* s, BYTE type, UINT16 channel_id) { BOOL rc = FALSE; size_t length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); WLog_DBG(TAG, "%s: sending data (type=0x%x size=%" PRIuz " channelId=%" PRIu16 ")", __FUNCTION__, type, Stream_Length(s), channel_id); rdp->outPackets++; if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags) { BOOL rc = FALSE; UINT16 length; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId); if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } static BOOL rdp_recv_server_shutdown_denied_pdu(rdpRdp* rdp, wStream* s) { return TRUE; } static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT16 ledFlags; rdpContext* context = rdp->instance->context; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */ IFCALL(context->update->SetKeyboardIndicators, context, ledFlags); return TRUE; } static BOOL rdp_recv_server_set_keyboard_ime_status_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT32 imeState; UINT32 imeConvMode; if (!rdp || !rdp->input) return FALSE; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT32(s, imeState); /* imeState (4 bytes) */ Stream_Read_UINT32(s, imeConvMode); /* imeConvMode (4 bytes) */ IFCALL(rdp->update->SetKeyboardImeStatus, rdp->context, unitId, imeState, imeConvMode); return TRUE; } static BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, wStream* s) { UINT32 errorInfo; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, errorInfo); /* errorInfo (4 bytes) */ return rdp_set_error_info(rdp, errorInfo); } static BOOL rdp_recv_server_auto_reconnect_status_pdu(rdpRdp* rdp, wStream* s) { UINT32 arcStatus; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, arcStatus); /* arcStatus (4 bytes) */ WLog_WARN(TAG, "AutoReconnectStatus: 0x%08" PRIX32 "", arcStatus); return TRUE; } static BOOL rdp_recv_server_status_info_pdu(rdpRdp* rdp, wStream* s) { UINT32 statusCode; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, statusCode); /* statusCode (4 bytes) */ if (rdp->update->ServerStatusInfo) return rdp->update->ServerStatusInfo(rdp->context, statusCode); return TRUE; } static BOOL rdp_recv_monitor_layout_pdu(rdpRdp* rdp, wStream* s) { UINT32 index; UINT32 monitorCount; MONITOR_DEF* monitor; MONITOR_DEF* monitorDefArray; BOOL ret = TRUE; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, monitorCount); /* monitorCount (4 bytes) */ if ((Stream_GetRemainingLength(s) / 20) < monitorCount) return FALSE; monitorDefArray = (MONITOR_DEF*)calloc(monitorCount, sizeof(MONITOR_DEF)); if (!monitorDefArray) return FALSE; for (monitor = monitorDefArray, index = 0; index < monitorCount; index++, monitor++) { Stream_Read_UINT32(s, monitor->left); /* left (4 bytes) */ Stream_Read_UINT32(s, monitor->top); /* top (4 bytes) */ Stream_Read_UINT32(s, monitor->right); /* right (4 bytes) */ Stream_Read_UINT32(s, monitor->bottom); /* bottom (4 bytes) */ Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */ } IFCALLRET(rdp->update->RemoteMonitors, ret, rdp->context, monitorCount, monitorDefArray); free(monitorDefArray); return ret; } int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { BYTE type; wStream* cs; UINT16 length; UINT32 shareId; BYTE compressedType; UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) { WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; } cs = s; if (compressedType & PACKET_COMPRESSED) { UINT32 DstSize = 0; BYTE* pDstData = NULL; UINT16 SrcSize = compressedLength - 18; if ((compressedLength < 18) || (Stream_GetRemainingLength(s) < SrcSize)) { WLog_ERR(TAG, "bulk_decompress: not enough bytes for compressedLength %" PRIu16 "", compressedLength); return -1; } if (bulk_decompress(rdp->bulk, Stream_Pointer(s), SrcSize, &pDstData, &DstSize, compressedType)) { if (!(cs = StreamPool_Take(rdp->transport->ReceivePool, DstSize))) { WLog_ERR(TAG, "Couldn't take stream from pool"); return -1; } Stream_SetPosition(cs, 0); Stream_Write(cs, pDstData, DstSize); Stream_SealLength(cs); Stream_SetPosition(cs, 0); } else { WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } Stream_Seek(s, SrcSize); } WLog_DBG(TAG, "recv %s Data PDU (0x%02" PRIX8 "), length: %" PRIu16 "", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - " "rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - " "rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - " "rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; } break; default: break; } if (cs != s) Stream_Release(cs); return 0; out_fail: if (cs != s) Stream_Release(cs); return -1; } int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ return rdp_recv_autodetect_request_packet(rdp, s); } if (securityFlags & SEC_AUTODETECT_RSP) { /* Client Auto-Detect Response PDU */ return rdp_recv_autodetect_response_packet(rdp, s); } if (securityFlags & SEC_HEARTBEAT) { /* Heartbeat PDU */ return rdp_recv_heartbeat_packet(rdp, s); } if (securityFlags & SEC_TRANSPORT_REQ) { /* Initiate Multitransport Request PDU */ return rdp_recv_multitransport_packet(rdp, s); } return -1; } int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return -1; if (type == PDU_TYPE_DATA) { return rdp_recv_data_pdu(rdp, s); } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else if (type == PDU_TYPE_FLOW_RESPONSE || type == PDU_TYPE_FLOW_STOP || type == PDU_TYPE_FLOW_TEST) { return 0; } else { return -1; } } BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; if (!type) return FALSE; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ return TRUE; } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, wStream* s, UINT16* pLength, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; BOOL status; INT32 length; if (!rdp || !s || !pLength) return FALSE; length = *pLength; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; INT64 padLength; if (Stream_GetRemainingLength(s) < 12) return FALSE; Stream_Read_UINT16(s, len); /* 0x10 */ Stream_Read_UINT8(s, version); /* 0x1 */ Stream_Read_UINT8(s, pad); sig = Stream_Pointer(s); Stream_Seek(s, 8); /* signature */ length -= 12; padLength = length - pad; if ((length <= 0) || (padLength <= 0)) return FALSE; if (!security_fips_decrypt(Stream_Pointer(s), length, rdp)) { WLog_ERR(TAG, "FATAL: cannot decrypt"); return FALSE; /* TODO */ } if (!security_fips_check_signature(Stream_Pointer(s), length - pad, sig, rdp)) { WLog_ERR(TAG, "FATAL: invalid packet signature"); return FALSE; /* TODO */ } Stream_SetLength(s, Stream_Length(s) - pad); *pLength = padLength; return TRUE; } if (Stream_GetRemainingLength(s) < sizeof(wmac)) return FALSE; Stream_Read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (length <= 0) return FALSE; if (!security_decrypt(Stream_Pointer(s), length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, Stream_Pointer(s), length, FALSE, cmac); else status = security_mac_signature(rdp, Stream_Pointer(s), length, cmac); if (!status) return FALSE; if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { WLog_ERR(TAG, "WARNING: invalid packet signature"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ // return FALSE; } *pLength = length; return TRUE; } static const char* pdu_type_to_str(UINT16 pduType) { static char buffer[1024] = { 0 }; switch (pduType) { case PDU_TYPE_DEMAND_ACTIVE: return "PDU_TYPE_DEMAND_ACTIVE"; case PDU_TYPE_CONFIRM_ACTIVE: return "PDU_TYPE_CONFIRM_ACTIVE"; case PDU_TYPE_DEACTIVATE_ALL: return "PDU_TYPE_DEACTIVATE_ALL"; case PDU_TYPE_DATA: return "PDU_TYPE_DATA"; case PDU_TYPE_SERVER_REDIRECTION: return "PDU_TYPE_SERVER_REDIRECTION"; case PDU_TYPE_FLOW_TEST: return "PDU_TYPE_FLOW_TEST"; case PDU_TYPE_FLOW_RESPONSE: return "PDU_TYPE_FLOW_RESPONSE"; case PDU_TYPE_FLOW_STOP: return "PDU_TYPE_FLOW_STOP"; default: _snprintf(buffer, sizeof(buffer), "UNKNOWN %04" PRIx16, pduType); return buffer; } } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) { int rc = 0; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId = 0; UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, &length, &channelId)) { WLog_ERR(TAG, "Incorrect RDP header."); return -1; } if (freerdp_shall_disconnect(rdp->instance)) return 0; if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, &length)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, &length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ Stream_Rewind(s, 2); rdp->inPackets++; rc = rdp_recv_enhanced_security_redirection_packet(rdp, s); goto out; } } if (channelId == MCS_GLOBAL_CHANNEL_ID) { while (Stream_GetRemainingLength(s) > 3) { size_t startheader, endheader, start, end, diff, headerdiff; startheader = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; } start = endheader = Stream_GetPosition(s); headerdiff = endheader - startheader; if (pduLength < headerdiff) { WLog_ERR( TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() invalid pduLength %" PRIu16, pduLength); return -1; } pduLength -= headerdiff; rdp->settings->PduSource = pduSource; rdp->inPackets++; switch (pduType) { case PDU_TYPE_DATA: rc = rdp_recv_data_pdu(rdp, s); if (rc < 0) return rc; break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; } break; case PDU_TYPE_SERVER_REDIRECTION: return rdp_recv_enhanced_security_redirection_packet(rdp, s); case PDU_TYPE_FLOW_RESPONSE: case PDU_TYPE_FLOW_STOP: case PDU_TYPE_FLOW_TEST: WLog_DBG(TAG, "flow message 0x%04" PRIX16 "", pduType); /* http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (!Stream_SafeSeek(s, pduLength)) return -1; break; default: WLog_ERR(TAG, "incorrect PDU type: 0x%04" PRIX16 "", pduType); break; } end = Stream_GetPosition(s); diff = end - start; if (diff != pduLength) { WLog_WARN(TAG, "pduType %s not properly parsed, %" PRIdz " bytes remaining unhandled. Skipping.", pdu_type_to_str(pduType), diff); if (!Stream_SafeSeek(s, pduLength)) return -1; } } } else if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId)) { if (!rdp->settings->UseRdpSecurityLayer) if (!rdp_read_security_header(s, &securityFlags, NULL)) return -1; rdp->inPackets++; rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { rdp->inPackets++; if (!freerdp_channel_process(rdp->instance, s, channelId, length)) return -1; } out: if (!tpkt_ensure_stream_consumed(s, length)) return -1; return rc; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { WLog_ERR(TAG, "incorrect FastPath PDU header length %" PRIu16 "", length); return -1; } if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, &length, flags)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; } } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, wStream* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*)extra; /* * At any point in the connection sequence between when all * MCS channels have been joined and when the RDP connection * enters the active state, an auto-detect PDU can be received * on the MCS message channel. */ if ((rdp->state > CONNECTION_STATE_MCS_CHANNEL_JOIN) && (rdp->state < CONNECTION_STATE_ACTIVE)) { if (rdp_client_connect_auto_detect(rdp, s)) return 0; } switch (rdp->state) { case CONNECTION_STATE_NLA: if (nla_get_state(rdp->nla) < NLA_STATE_AUTH_INFO) { if (nla_recv_pdu(rdp->nla, s) < 1) { WLog_ERR(TAG, "%s: %s - nla_recv_pdu() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } else if (nla_get_state(rdp->nla) == NLA_STATE_POST_NEGO) { nego_recv(rdp->transport, s, (void*)rdp->nego); if (nego_get_state(rdp->nego) != NEGO_STATE_FINAL) { WLog_ERR(TAG, "%s: %s - nego_recv() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } if (nla_get_state(rdp->nla) == NLA_STATE_AUTH_INFO) { transport_set_nla_mode(rdp->transport, FALSE); if (rdp->settings->VmConnectMode) { if (!nego_set_state(rdp->nego, NEGO_STATE_NLA)) return -1; if (!nego_set_requested_protocols(rdp->nego, PROTOCOL_HYBRID | PROTOCOL_SSL)) return -1; nego_send_negotiation_request(rdp->nego); if (!nla_set_state(rdp->nla, NLA_STATE_POST_NEGO)) return -1; } else { if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } } if (nla_get_state(rdp->nla) == NLA_STATE_FINAL) { nla_free(rdp->nla); rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) { WLog_ERR(TAG, "%s: %s - mcs_client_begin() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } break; case CONNECTION_STATE_MCS_CONNECT: if (!mcs_recv_connect_response(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_connect_response failure"); return -1; } if (!mcs_send_erect_domain_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_erect_domain_request failure"); return -1; } if (!mcs_send_attach_user_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_attach_user_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER); break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!mcs_recv_attach_user_confirm(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_attach_user_confirm failure"); return -1; } if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->userId)) { WLog_ERR(TAG, "mcs_send_channel_join_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN); break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) { WLog_ERR(TAG, "%s: %s - " "rdp_client_connect_mcs_channel_join_confirm() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); status = -1; } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_client_connect_license() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - " "rdp_client_connect_demand_active() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) { ActivatedEventArgs activatedEvent; rdpContext* context = rdp->context; rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); EventArgsInit(&activatedEvent, "libfreerdp"); activatedEvent.firstActivation = !rdp->deactivation_reactivation; PubSub_OnActivated(context->pubSub, context, &activatedEvent); return 2; } if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; default: WLog_ERR(TAG, "%s: %s state %d", __FUNCTION__, rdp_server_connection_state_string(rdp->state), rdp->state); status = -1; break; } return status; } BOOL rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, const BYTE* data, size_t size) { return freerdp_channel_send(rdp, channelId, data, size); } BOOL rdp_send_error_info(rdpRdp* rdp) { wStream* s; BOOL status; if (rdp->errorInfo == ERRINFO_SUCCESS) return TRUE; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, rdp->errorInfo); /* error id (4 bytes) */ status = rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_ERROR_INFO, 0); return status; } int rdp_check_fds(rdpRdp* rdp) { int status; rdpTransport* transport = rdp->transport; if (transport->tsg) { rdpTsg* tsg = transport->tsg; if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles()"); return -1; } if (tsg_get_state(tsg) != TSG_STATE_PIPE_CREATED) return 1; } status = transport_check_fds(transport); if (status == 1) { if (!rdp_client_redirect(rdp)) /* session redirection */ return -1; } if (status < 0) WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } BOOL freerdp_get_stats(rdpRdp* rdp, UINT64* inBytes, UINT64* outBytes, UINT64* inPackets, UINT64* outPackets) { if (!rdp) return FALSE; if (inBytes) *inBytes = rdp->inBytes; if (outBytes) *outBytes = rdp->outBytes; if (inPackets) *inPackets = rdp->inPackets; if (outPackets) *outPackets = rdp->outPackets; return TRUE; } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(rdpContext* context) { rdpRdp* rdp; DWORD flags; BOOL newSettings = FALSE; rdp = (rdpRdp*)calloc(1, sizeof(rdpRdp)); if (!rdp) return NULL; rdp->context = context; rdp->instance = context->instance; flags = 0; if (context->ServerMode) flags |= FREERDP_SETTINGS_SERVER_MODE; if (!context->settings) { context->settings = freerdp_settings_new(flags); if (!context->settings) goto out_free; newSettings = TRUE; } rdp->settings = context->settings; if (context->instance) { rdp->settings->instance = context->instance; context->instance->settings = rdp->settings; } else if (context->peer) { rdp->settings->instance = context->peer; context->peer->settings = rdp->settings; } rdp->transport = transport_new(context); if (!rdp->transport) goto out_free_settings; rdp->license = license_new(rdp); if (!rdp->license) goto out_free_transport; rdp->input = input_new(rdp); if (!rdp->input) goto out_free_license; rdp->update = update_new(rdp); if (!rdp->update) goto out_free_input; rdp->fastpath = fastpath_new(rdp); if (!rdp->fastpath) goto out_free_update; rdp->nego = nego_new(rdp->transport); if (!rdp->nego) goto out_free_fastpath; rdp->mcs = mcs_new(rdp->transport); if (!rdp->mcs) goto out_free_nego; rdp->redirection = redirection_new(); if (!rdp->redirection) goto out_free_mcs; rdp->autodetect = autodetect_new(); if (!rdp->autodetect) goto out_free_redirection; rdp->heartbeat = heartbeat_new(); if (!rdp->heartbeat) goto out_free_autodetect; rdp->multitransport = multitransport_new(); if (!rdp->multitransport) goto out_free_heartbeat; rdp->bulk = bulk_new(context); if (!rdp->bulk) goto out_free_multitransport; return rdp; out_free_multitransport: multitransport_free(rdp->multitransport); out_free_heartbeat: heartbeat_free(rdp->heartbeat); out_free_autodetect: autodetect_free(rdp->autodetect); out_free_redirection: redirection_free(rdp->redirection); out_free_mcs: mcs_free(rdp->mcs); out_free_nego: nego_free(rdp->nego); out_free_fastpath: fastpath_free(rdp->fastpath); out_free_update: update_free(rdp->update); out_free_input: input_free(rdp->input); out_free_license: license_free(rdp->license); out_free_transport: transport_free(rdp->transport); out_free_settings: if (newSettings) freerdp_settings_free(rdp->settings); out_free: free(rdp); return NULL; } void rdp_reset(rdpRdp* rdp) { rdpContext* context; rdpSettings* settings; context = rdp->context; settings = rdp->settings; bulk_reset(rdp->bulk); if (rdp->rc4_decrypt_key) { winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = NULL; } if (rdp->rc4_encrypt_key) { winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = NULL; } if (rdp->fips_encrypt) { winpr_Cipher_Free(rdp->fips_encrypt); rdp->fips_encrypt = NULL; } if (rdp->fips_decrypt) { winpr_Cipher_Free(rdp->fips_decrypt); rdp->fips_decrypt = NULL; } if (settings->ServerRandom) { free(settings->ServerRandom); settings->ServerRandom = NULL; settings->ServerRandomLength = 0; } if (settings->ServerCertificate) { free(settings->ServerCertificate); settings->ServerCertificate = NULL; } if (settings->ClientAddress) { free(settings->ClientAddress); settings->ClientAddress = NULL; } mcs_free(rdp->mcs); nego_free(rdp->nego); license_free(rdp->license); transport_free(rdp->transport); fastpath_free(rdp->fastpath); rdp->transport = transport_new(context); rdp->license = license_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->fastpath = fastpath_new(rdp); rdp->transport->layer = TRANSPORT_LAYER_TCP; rdp->errorInfo = 0; rdp->deactivation_reactivation = 0; rdp->finalize_sc_pdus = 0; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp) { winpr_RC4_Free(rdp->rc4_decrypt_key); winpr_RC4_Free(rdp->rc4_encrypt_key); winpr_Cipher_Free(rdp->fips_encrypt); winpr_Cipher_Free(rdp->fips_decrypt); freerdp_settings_free(rdp->settings); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); nla_free(rdp->nla); redirection_free(rdp->redirection); autodetect_free(rdp->autodetect); heartbeat_free(rdp->heartbeat); multitransport_free(rdp->multitransport); bulk_free(rdp->bulk); free(rdp); } }
void rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ }
BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; if (!type) return FALSE; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ return TRUE; }
{'added': [(105, 'static BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type);'), (148, '\tUINT16 len;'), (153, '\tStream_Read_UINT16(s, len); /* totalLength */'), (154, ''), (155, '\t*length = len;'), (159, '\tif (len == 0x8000)'), (161, '\t\tif (!rdp_read_flow_control_pdu(s, type))'), (162, '\t\t\treturn FALSE;'), (168, '\tif ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s)))'), (174, '\tif (len > 4)'), (1123, 'BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type)'), (1133, '\tif (!type)'), (1134, '\t\treturn FALSE;'), (1135, '\tif (Stream_GetRemainingLength(s) < 6)'), (1136, '\t\treturn FALSE;'), (1143, '\treturn TRUE;')], 'deleted': [(105, 'static void rdp_read_flow_control_pdu(wStream* s, UINT16* type);'), (152, '\tStream_Read_UINT16(s, *length); /* totalLength */'), (156, '\tif (*length == 0x8000)'), (158, '\t\trdp_read_flow_control_pdu(s, type);'), (164, '\tif (((size_t)*length - 2) > Stream_GetRemainingLength(s))'), (170, '\tif (*length > 4)'), (1119, 'void rdp_read_flow_control_pdu(wStream* s, UINT16* type)')]}
16
7
1,482
7,621
https://github.com/FreeRDP/FreeRDP
CVE-2020-11048
['CWE-125']
rdp.c
rdp_read_share_control_header
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.rdp") const char* DATA_PDU_TYPE_STRINGS[80] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout", /* 0x37 */ "FrameAcknowledge", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; static void rdp_read_flow_control_pdu(wStream* s, UINT16* type); static void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id); static void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id); /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(wStream* s, UINT16* flags, UINT16* length) { /* Basic Security Header */ if ((Stream_GetRemainingLength(s) < 4) || (length && (*length < 4))) return FALSE; Stream_Read_UINT16(s, *flags); /* flags */ Stream_Seek(s, 2); /* flagsHi (unused) */ if (length) *length -= 4; return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(wStream* s, UINT16 flags) { /* Basic Security Header */ Stream_Write_UINT16(s, flags); /* flags */ Stream_Write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, *length); /* totalLength */ /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (*length == 0x8000) { rdp_read_flow_control_pdu(s, type); *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if (((size_t)*length - 2) > Stream_GetRemainingLength(s)) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (*length > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ Stream_Write_UINT16(s, length); /* totalLength */ Stream_Write_UINT16(s, type | 0x10); /* pduType */ Stream_Write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(wStream* s, UINT16* length, BYTE* type, UINT32* shareId, BYTE* compressedType, UINT16* compressedLength) { if (Stream_GetRemainingLength(s) < 12) return FALSE; /* Share Data Header */ Stream_Read_UINT32(s, *shareId); /* shareId (4 bytes) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT8(s); /* streamId (1 byte) */ Stream_Read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ Stream_Read_UINT8(s, *type); /* pduType2, Data PDU Type (1 byte) */ Stream_Read_UINT8(s, *compressedType); /* compressedType (1 byte) */ Stream_Read_UINT16(s, *compressedLength); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ Stream_Write_UINT32(s, share_id); /* shareId (4 bytes) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT8(s, STREAM_LOW); /* streamId (1 byte) */ Stream_Write_UINT16(s, length); /* uncompressedLength (2 bytes) */ Stream_Write_UINT8(s, type); /* pduType2, Data PDU Type (1 byte) */ Stream_Write_UINT8(s, 0); /* compressedType (1 byte) */ Stream_Write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static BOOL rdp_security_stream_init(rdpRdp* rdp, wStream* s, BOOL sec_header) { if (!rdp || !s) return FALSE; if (rdp->do_crypt) { if (!Stream_SafeSeek(s, 12)) return FALSE; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { if (!Stream_SafeSeek(s, 4)) return FALSE; } rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0 || sec_header) { if (!Stream_SafeSeek(s, 4)) return FALSE; } return TRUE; } wStream* rdp_send_stream_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, FALSE)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_send_stream_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_CONTROL_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_data_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_DATA_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } BOOL rdp_set_error_info(rdpRdp* rdp, UINT32 errorInfo) { rdp->errorInfo = errorInfo; if (rdp->errorInfo != ERRINFO_SUCCESS) { rdpContext* context = rdp->context; rdp_print_errinfo(rdp->errorInfo); if (context) { freerdp_set_last_error_log(context, MAKE_FREERDP_ERROR(ERRINFO, errorInfo)); if (context->pubSub) { ErrorInfoEventArgs e; EventArgsInit(&e, "freerdp"); e.code = rdp->errorInfo; PubSub_OnErrorInfo(context->pubSub, context, &e); } } else WLog_ERR(TAG, "%s missing context=%p", __FUNCTION__, context); } else { freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SUCCESS); } return TRUE; } wStream* rdp_message_channel_pdu_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, TRUE)) goto fail; return s; fail: Stream_Release(s); return NULL; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, wStream* s, UINT16* length, UINT16* channelId) { BYTE li; BYTE byte; BYTE code; BYTE choice; UINT16 initiator; enum DomainMCSPDU MCSPDU; enum DomainMCSPDU domainMCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!tpkt_read_header(s, length)) return FALSE; if (!tpdu_read_header(s, &code, &li, *length)) return FALSE; if (code != X224_TPDU_DATA) { if (code == X224_TPDU_DISCONNECT_REQUEST) { freerdp_abort_connect(rdp->instance); return TRUE; } return FALSE; } if (!per_read_choice(s, &choice)) return FALSE; domainMCSPDU = (enum DomainMCSPDU)(choice >> 2); if (domainMCSPDU != MCSPDU) { if (domainMCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } MCSPDU = domainMCSPDU; if (*length < 8U) return FALSE; if ((*length - 8U) > Stream_GetRemainingLength(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { int reason = 0; TerminateEventArgs e; rdpContext* context; if (!mcs_recv_disconnect_provider_ultimatum(rdp->mcs, s, &reason)) return FALSE; if (!rdp->instance) return FALSE; context = rdp->instance->context; context->disconnectUltimatum = reason; if (rdp->errorInfo == ERRINFO_SUCCESS) { /** * Some servers like Windows Server 2008 R2 do not send the error info pdu * when the user logs off like they should. Map DisconnectProviderUltimatum * to a ERRINFO_LOGOFF_BY_USER when the errinfo code is ERRINFO_SUCCESS. */ if (reason == Disconnect_Ultimatum_provider_initiated) rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); else if (reason == Disconnect_Ultimatum_user_requested) rdp_set_error_info(rdp, ERRINFO_LOGOFF_BY_USER); else rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); } WLog_DBG(TAG, "DisconnectProviderUltimatum: reason: %d", reason); freerdp_abort_connect(rdp->instance); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); return TRUE; } if (Stream_GetRemainingLength(s) < 5) return FALSE; if (!per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID)) /* initiator (UserId) */ return FALSE; if (!per_read_integer16(s, channelId, 0)) /* channelId */ return FALSE; Stream_Read_UINT8(s, byte); /* dataPriority + Segmentation (0x70) */ if (!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > Stream_GetRemainingLength(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, wStream* s, UINT16 length, UINT16 channelId) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->userId, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channelId, 0); /* channelId */ Stream_Write_UINT8(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, even though we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; Stream_Write_UINT16_BE(s, length); /* userData (OCTET_STRING) */ } static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, int length, UINT32 sec_flags, UINT32* pad) { BYTE* data; BOOL status; sec_flags |= rdp->sec_flags; *pad = 0; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = Stream_Pointer(s) + 12; length = length - (data - Stream_Buffer(s)); Stream_Write_UINT16(s, 0x10); /* length */ Stream_Write_UINT8(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ *pad = 8 - (length % 8); if (*pad == 8) *pad = 0; if (*pad) memset(data + length, 0, *pad); Stream_Write_UINT8(s, *pad); if (!security_hmac_signature(data, length, Stream_Pointer(s), rdp)) return FALSE; Stream_Seek(s, 8); security_fips_encrypt(data, length + *pad, rdp); } else { data = Stream_Pointer(s) + 8; length = length - (data - Stream_Buffer(s)); if (sec_flags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, data, length, TRUE, Stream_Pointer(s)); else status = security_mac_signature(rdp, data, length, Stream_Pointer(s)); if (!status) return FALSE; Stream_Seek(s, 8); if (!security_encrypt(Stream_Pointer(s), length, rdp)) return FALSE; } } rdp->sec_flags = 0; } return TRUE; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp, UINT16 sec_flags) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0 || sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet. * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, wStream* s, UINT16 channel_id) { BOOL rc = FALSE; UINT32 pad; UINT16 length; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, channel_id); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_pdu(rdpRdp* rdp, wStream* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!rdp || !s) return FALSE; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) return FALSE; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, wStream* s, BYTE type, UINT16 channel_id) { BOOL rc = FALSE; size_t length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); WLog_DBG(TAG, "%s: sending data (type=0x%x size=%" PRIuz " channelId=%" PRIu16 ")", __FUNCTION__, type, Stream_Length(s), channel_id); rdp->outPackets++; if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags) { BOOL rc = FALSE; UINT16 length; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId); if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } static BOOL rdp_recv_server_shutdown_denied_pdu(rdpRdp* rdp, wStream* s) { return TRUE; } static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT16 ledFlags; rdpContext* context = rdp->instance->context; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */ IFCALL(context->update->SetKeyboardIndicators, context, ledFlags); return TRUE; } static BOOL rdp_recv_server_set_keyboard_ime_status_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT32 imeState; UINT32 imeConvMode; if (!rdp || !rdp->input) return FALSE; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT32(s, imeState); /* imeState (4 bytes) */ Stream_Read_UINT32(s, imeConvMode); /* imeConvMode (4 bytes) */ IFCALL(rdp->update->SetKeyboardImeStatus, rdp->context, unitId, imeState, imeConvMode); return TRUE; } static BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, wStream* s) { UINT32 errorInfo; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, errorInfo); /* errorInfo (4 bytes) */ return rdp_set_error_info(rdp, errorInfo); } static BOOL rdp_recv_server_auto_reconnect_status_pdu(rdpRdp* rdp, wStream* s) { UINT32 arcStatus; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, arcStatus); /* arcStatus (4 bytes) */ WLog_WARN(TAG, "AutoReconnectStatus: 0x%08" PRIX32 "", arcStatus); return TRUE; } static BOOL rdp_recv_server_status_info_pdu(rdpRdp* rdp, wStream* s) { UINT32 statusCode; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, statusCode); /* statusCode (4 bytes) */ if (rdp->update->ServerStatusInfo) return rdp->update->ServerStatusInfo(rdp->context, statusCode); return TRUE; } static BOOL rdp_recv_monitor_layout_pdu(rdpRdp* rdp, wStream* s) { UINT32 index; UINT32 monitorCount; MONITOR_DEF* monitor; MONITOR_DEF* monitorDefArray; BOOL ret = TRUE; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, monitorCount); /* monitorCount (4 bytes) */ if ((Stream_GetRemainingLength(s) / 20) < monitorCount) return FALSE; monitorDefArray = (MONITOR_DEF*)calloc(monitorCount, sizeof(MONITOR_DEF)); if (!monitorDefArray) return FALSE; for (monitor = monitorDefArray, index = 0; index < monitorCount; index++, monitor++) { Stream_Read_UINT32(s, monitor->left); /* left (4 bytes) */ Stream_Read_UINT32(s, monitor->top); /* top (4 bytes) */ Stream_Read_UINT32(s, monitor->right); /* right (4 bytes) */ Stream_Read_UINT32(s, monitor->bottom); /* bottom (4 bytes) */ Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */ } IFCALLRET(rdp->update->RemoteMonitors, ret, rdp->context, monitorCount, monitorDefArray); free(monitorDefArray); return ret; } int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { BYTE type; wStream* cs; UINT16 length; UINT32 shareId; BYTE compressedType; UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) { WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; } cs = s; if (compressedType & PACKET_COMPRESSED) { UINT32 DstSize = 0; BYTE* pDstData = NULL; UINT16 SrcSize = compressedLength - 18; if ((compressedLength < 18) || (Stream_GetRemainingLength(s) < SrcSize)) { WLog_ERR(TAG, "bulk_decompress: not enough bytes for compressedLength %" PRIu16 "", compressedLength); return -1; } if (bulk_decompress(rdp->bulk, Stream_Pointer(s), SrcSize, &pDstData, &DstSize, compressedType)) { if (!(cs = StreamPool_Take(rdp->transport->ReceivePool, DstSize))) { WLog_ERR(TAG, "Couldn't take stream from pool"); return -1; } Stream_SetPosition(cs, 0); Stream_Write(cs, pDstData, DstSize); Stream_SealLength(cs); Stream_SetPosition(cs, 0); } else { WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } Stream_Seek(s, SrcSize); } WLog_DBG(TAG, "recv %s Data PDU (0x%02" PRIX8 "), length: %" PRIu16 "", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - " "rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - " "rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - " "rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; } break; default: break; } if (cs != s) Stream_Release(cs); return 0; out_fail: if (cs != s) Stream_Release(cs); return -1; } int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ return rdp_recv_autodetect_request_packet(rdp, s); } if (securityFlags & SEC_AUTODETECT_RSP) { /* Client Auto-Detect Response PDU */ return rdp_recv_autodetect_response_packet(rdp, s); } if (securityFlags & SEC_HEARTBEAT) { /* Heartbeat PDU */ return rdp_recv_heartbeat_packet(rdp, s); } if (securityFlags & SEC_TRANSPORT_REQ) { /* Initiate Multitransport Request PDU */ return rdp_recv_multitransport_packet(rdp, s); } return -1; } int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return -1; if (type == PDU_TYPE_DATA) { return rdp_recv_data_pdu(rdp, s); } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else if (type == PDU_TYPE_FLOW_RESPONSE || type == PDU_TYPE_FLOW_STOP || type == PDU_TYPE_FLOW_TEST) { return 0; } else { return -1; } } void rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, wStream* s, UINT16* pLength, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; BOOL status; INT32 length; if (!rdp || !s || !pLength) return FALSE; length = *pLength; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; INT64 padLength; if (Stream_GetRemainingLength(s) < 12) return FALSE; Stream_Read_UINT16(s, len); /* 0x10 */ Stream_Read_UINT8(s, version); /* 0x1 */ Stream_Read_UINT8(s, pad); sig = Stream_Pointer(s); Stream_Seek(s, 8); /* signature */ length -= 12; padLength = length - pad; if ((length <= 0) || (padLength <= 0)) return FALSE; if (!security_fips_decrypt(Stream_Pointer(s), length, rdp)) { WLog_ERR(TAG, "FATAL: cannot decrypt"); return FALSE; /* TODO */ } if (!security_fips_check_signature(Stream_Pointer(s), length - pad, sig, rdp)) { WLog_ERR(TAG, "FATAL: invalid packet signature"); return FALSE; /* TODO */ } Stream_SetLength(s, Stream_Length(s) - pad); *pLength = padLength; return TRUE; } if (Stream_GetRemainingLength(s) < sizeof(wmac)) return FALSE; Stream_Read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (length <= 0) return FALSE; if (!security_decrypt(Stream_Pointer(s), length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, Stream_Pointer(s), length, FALSE, cmac); else status = security_mac_signature(rdp, Stream_Pointer(s), length, cmac); if (!status) return FALSE; if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { WLog_ERR(TAG, "WARNING: invalid packet signature"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ // return FALSE; } *pLength = length; return TRUE; } static const char* pdu_type_to_str(UINT16 pduType) { static char buffer[1024] = { 0 }; switch (pduType) { case PDU_TYPE_DEMAND_ACTIVE: return "PDU_TYPE_DEMAND_ACTIVE"; case PDU_TYPE_CONFIRM_ACTIVE: return "PDU_TYPE_CONFIRM_ACTIVE"; case PDU_TYPE_DEACTIVATE_ALL: return "PDU_TYPE_DEACTIVATE_ALL"; case PDU_TYPE_DATA: return "PDU_TYPE_DATA"; case PDU_TYPE_SERVER_REDIRECTION: return "PDU_TYPE_SERVER_REDIRECTION"; case PDU_TYPE_FLOW_TEST: return "PDU_TYPE_FLOW_TEST"; case PDU_TYPE_FLOW_RESPONSE: return "PDU_TYPE_FLOW_RESPONSE"; case PDU_TYPE_FLOW_STOP: return "PDU_TYPE_FLOW_STOP"; default: _snprintf(buffer, sizeof(buffer), "UNKNOWN %04" PRIx16, pduType); return buffer; } } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) { int rc = 0; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId = 0; UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, &length, &channelId)) { WLog_ERR(TAG, "Incorrect RDP header."); return -1; } if (freerdp_shall_disconnect(rdp->instance)) return 0; if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, &length)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, &length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ Stream_Rewind(s, 2); rdp->inPackets++; rc = rdp_recv_enhanced_security_redirection_packet(rdp, s); goto out; } } if (channelId == MCS_GLOBAL_CHANNEL_ID) { while (Stream_GetRemainingLength(s) > 3) { size_t startheader, endheader, start, end, diff, headerdiff; startheader = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; } start = endheader = Stream_GetPosition(s); headerdiff = endheader - startheader; if (pduLength < headerdiff) { WLog_ERR( TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() invalid pduLength %" PRIu16, pduLength); return -1; } pduLength -= headerdiff; rdp->settings->PduSource = pduSource; rdp->inPackets++; switch (pduType) { case PDU_TYPE_DATA: rc = rdp_recv_data_pdu(rdp, s); if (rc < 0) return rc; break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; } break; case PDU_TYPE_SERVER_REDIRECTION: return rdp_recv_enhanced_security_redirection_packet(rdp, s); case PDU_TYPE_FLOW_RESPONSE: case PDU_TYPE_FLOW_STOP: case PDU_TYPE_FLOW_TEST: WLog_DBG(TAG, "flow message 0x%04" PRIX16 "", pduType); /* http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (!Stream_SafeSeek(s, pduLength)) return -1; break; default: WLog_ERR(TAG, "incorrect PDU type: 0x%04" PRIX16 "", pduType); break; } end = Stream_GetPosition(s); diff = end - start; if (diff != pduLength) { WLog_WARN(TAG, "pduType %s not properly parsed, %" PRIdz " bytes remaining unhandled. Skipping.", pdu_type_to_str(pduType), diff); if (!Stream_SafeSeek(s, pduLength)) return -1; } } } else if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId)) { if (!rdp->settings->UseRdpSecurityLayer) if (!rdp_read_security_header(s, &securityFlags, NULL)) return -1; rdp->inPackets++; rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { rdp->inPackets++; if (!freerdp_channel_process(rdp->instance, s, channelId, length)) return -1; } out: if (!tpkt_ensure_stream_consumed(s, length)) return -1; return rc; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { WLog_ERR(TAG, "incorrect FastPath PDU header length %" PRIu16 "", length); return -1; } if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, &length, flags)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; } } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, wStream* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*)extra; /* * At any point in the connection sequence between when all * MCS channels have been joined and when the RDP connection * enters the active state, an auto-detect PDU can be received * on the MCS message channel. */ if ((rdp->state > CONNECTION_STATE_MCS_CHANNEL_JOIN) && (rdp->state < CONNECTION_STATE_ACTIVE)) { if (rdp_client_connect_auto_detect(rdp, s)) return 0; } switch (rdp->state) { case CONNECTION_STATE_NLA: if (nla_get_state(rdp->nla) < NLA_STATE_AUTH_INFO) { if (nla_recv_pdu(rdp->nla, s) < 1) { WLog_ERR(TAG, "%s: %s - nla_recv_pdu() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } else if (nla_get_state(rdp->nla) == NLA_STATE_POST_NEGO) { nego_recv(rdp->transport, s, (void*)rdp->nego); if (nego_get_state(rdp->nego) != NEGO_STATE_FINAL) { WLog_ERR(TAG, "%s: %s - nego_recv() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } if (nla_get_state(rdp->nla) == NLA_STATE_AUTH_INFO) { transport_set_nla_mode(rdp->transport, FALSE); if (rdp->settings->VmConnectMode) { if (!nego_set_state(rdp->nego, NEGO_STATE_NLA)) return -1; if (!nego_set_requested_protocols(rdp->nego, PROTOCOL_HYBRID | PROTOCOL_SSL)) return -1; nego_send_negotiation_request(rdp->nego); if (!nla_set_state(rdp->nla, NLA_STATE_POST_NEGO)) return -1; } else { if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } } if (nla_get_state(rdp->nla) == NLA_STATE_FINAL) { nla_free(rdp->nla); rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) { WLog_ERR(TAG, "%s: %s - mcs_client_begin() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } break; case CONNECTION_STATE_MCS_CONNECT: if (!mcs_recv_connect_response(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_connect_response failure"); return -1; } if (!mcs_send_erect_domain_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_erect_domain_request failure"); return -1; } if (!mcs_send_attach_user_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_attach_user_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER); break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!mcs_recv_attach_user_confirm(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_attach_user_confirm failure"); return -1; } if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->userId)) { WLog_ERR(TAG, "mcs_send_channel_join_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN); break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) { WLog_ERR(TAG, "%s: %s - " "rdp_client_connect_mcs_channel_join_confirm() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); status = -1; } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_client_connect_license() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - " "rdp_client_connect_demand_active() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) { ActivatedEventArgs activatedEvent; rdpContext* context = rdp->context; rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); EventArgsInit(&activatedEvent, "libfreerdp"); activatedEvent.firstActivation = !rdp->deactivation_reactivation; PubSub_OnActivated(context->pubSub, context, &activatedEvent); return 2; } if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; default: WLog_ERR(TAG, "%s: %s state %d", __FUNCTION__, rdp_server_connection_state_string(rdp->state), rdp->state); status = -1; break; } return status; } BOOL rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, const BYTE* data, size_t size) { return freerdp_channel_send(rdp, channelId, data, size); } BOOL rdp_send_error_info(rdpRdp* rdp) { wStream* s; BOOL status; if (rdp->errorInfo == ERRINFO_SUCCESS) return TRUE; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, rdp->errorInfo); /* error id (4 bytes) */ status = rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_ERROR_INFO, 0); return status; } int rdp_check_fds(rdpRdp* rdp) { int status; rdpTransport* transport = rdp->transport; if (transport->tsg) { rdpTsg* tsg = transport->tsg; if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles()"); return -1; } if (tsg_get_state(tsg) != TSG_STATE_PIPE_CREATED) return 1; } status = transport_check_fds(transport); if (status == 1) { if (!rdp_client_redirect(rdp)) /* session redirection */ return -1; } if (status < 0) WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } BOOL freerdp_get_stats(rdpRdp* rdp, UINT64* inBytes, UINT64* outBytes, UINT64* inPackets, UINT64* outPackets) { if (!rdp) return FALSE; if (inBytes) *inBytes = rdp->inBytes; if (outBytes) *outBytes = rdp->outBytes; if (inPackets) *inPackets = rdp->inPackets; if (outPackets) *outPackets = rdp->outPackets; return TRUE; } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(rdpContext* context) { rdpRdp* rdp; DWORD flags; BOOL newSettings = FALSE; rdp = (rdpRdp*)calloc(1, sizeof(rdpRdp)); if (!rdp) return NULL; rdp->context = context; rdp->instance = context->instance; flags = 0; if (context->ServerMode) flags |= FREERDP_SETTINGS_SERVER_MODE; if (!context->settings) { context->settings = freerdp_settings_new(flags); if (!context->settings) goto out_free; newSettings = TRUE; } rdp->settings = context->settings; if (context->instance) { rdp->settings->instance = context->instance; context->instance->settings = rdp->settings; } else if (context->peer) { rdp->settings->instance = context->peer; context->peer->settings = rdp->settings; } rdp->transport = transport_new(context); if (!rdp->transport) goto out_free_settings; rdp->license = license_new(rdp); if (!rdp->license) goto out_free_transport; rdp->input = input_new(rdp); if (!rdp->input) goto out_free_license; rdp->update = update_new(rdp); if (!rdp->update) goto out_free_input; rdp->fastpath = fastpath_new(rdp); if (!rdp->fastpath) goto out_free_update; rdp->nego = nego_new(rdp->transport); if (!rdp->nego) goto out_free_fastpath; rdp->mcs = mcs_new(rdp->transport); if (!rdp->mcs) goto out_free_nego; rdp->redirection = redirection_new(); if (!rdp->redirection) goto out_free_mcs; rdp->autodetect = autodetect_new(); if (!rdp->autodetect) goto out_free_redirection; rdp->heartbeat = heartbeat_new(); if (!rdp->heartbeat) goto out_free_autodetect; rdp->multitransport = multitransport_new(); if (!rdp->multitransport) goto out_free_heartbeat; rdp->bulk = bulk_new(context); if (!rdp->bulk) goto out_free_multitransport; return rdp; out_free_multitransport: multitransport_free(rdp->multitransport); out_free_heartbeat: heartbeat_free(rdp->heartbeat); out_free_autodetect: autodetect_free(rdp->autodetect); out_free_redirection: redirection_free(rdp->redirection); out_free_mcs: mcs_free(rdp->mcs); out_free_nego: nego_free(rdp->nego); out_free_fastpath: fastpath_free(rdp->fastpath); out_free_update: update_free(rdp->update); out_free_input: input_free(rdp->input); out_free_license: license_free(rdp->license); out_free_transport: transport_free(rdp->transport); out_free_settings: if (newSettings) freerdp_settings_free(rdp->settings); out_free: free(rdp); return NULL; } void rdp_reset(rdpRdp* rdp) { rdpContext* context; rdpSettings* settings; context = rdp->context; settings = rdp->settings; bulk_reset(rdp->bulk); if (rdp->rc4_decrypt_key) { winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = NULL; } if (rdp->rc4_encrypt_key) { winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = NULL; } if (rdp->fips_encrypt) { winpr_Cipher_Free(rdp->fips_encrypt); rdp->fips_encrypt = NULL; } if (rdp->fips_decrypt) { winpr_Cipher_Free(rdp->fips_decrypt); rdp->fips_decrypt = NULL; } if (settings->ServerRandom) { free(settings->ServerRandom); settings->ServerRandom = NULL; settings->ServerRandomLength = 0; } if (settings->ServerCertificate) { free(settings->ServerCertificate); settings->ServerCertificate = NULL; } if (settings->ClientAddress) { free(settings->ClientAddress); settings->ClientAddress = NULL; } mcs_free(rdp->mcs); nego_free(rdp->nego); license_free(rdp->license); transport_free(rdp->transport); fastpath_free(rdp->fastpath); rdp->transport = transport_new(context); rdp->license = license_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->fastpath = fastpath_new(rdp); rdp->transport->layer = TRANSPORT_LAYER_TCP; rdp->errorInfo = 0; rdp->deactivation_reactivation = 0; rdp->finalize_sc_pdus = 0; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp) { winpr_RC4_Free(rdp->rc4_decrypt_key); winpr_RC4_Free(rdp->rc4_encrypt_key); winpr_Cipher_Free(rdp->fips_encrypt); winpr_Cipher_Free(rdp->fips_decrypt); freerdp_settings_free(rdp->settings); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); nla_free(rdp->nla); redirection_free(rdp->redirection); autodetect_free(rdp->autodetect); heartbeat_free(rdp->heartbeat); multitransport_free(rdp->multitransport); bulk_free(rdp->bulk); free(rdp); } }
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Core * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include "rdp.h" #include "info.h" #include "redirection.h" #include <freerdp/crypto/per.h> #include <freerdp/log.h> #define TAG FREERDP_TAG("core.rdp") const char* DATA_PDU_TYPE_STRINGS[80] = { "?", "?", /* 0x00 - 0x01 */ "Update", /* 0x02 */ "?", "?", "?", "?", "?", "?", "?", "?", /* 0x03 - 0x0A */ "?", "?", "?", "?", "?", "?", "?", "?", "?", /* 0x0B - 0x13 */ "Control", /* 0x14 */ "?", "?", "?", "?", "?", "?", /* 0x15 - 0x1A */ "Pointer", /* 0x1B */ "Input", /* 0x1C */ "?", "?", /* 0x1D - 0x1E */ "Synchronize", /* 0x1F */ "?", /* 0x20 */ "Refresh Rect", /* 0x21 */ "Play Sound", /* 0x22 */ "Suppress Output", /* 0x23 */ "Shutdown Request", /* 0x24 */ "Shutdown Denied", /* 0x25 */ "Save Session Info", /* 0x26 */ "Font List", /* 0x27 */ "Font Map", /* 0x28 */ "Set Keyboard Indicators", /* 0x29 */ "?", /* 0x2A */ "Bitmap Cache Persistent List", /* 0x2B */ "Bitmap Cache Error", /* 0x2C */ "Set Keyboard IME Status", /* 0x2D */ "Offscreen Cache Error", /* 0x2E */ "Set Error Info", /* 0x2F */ "Draw Nine Grid Error", /* 0x30 */ "Draw GDI+ Error", /* 0x31 */ "ARC Status", /* 0x32 */ "?", "?", "?", /* 0x33 - 0x35 */ "Status Info", /* 0x36 */ "Monitor Layout", /* 0x37 */ "FrameAcknowledge", "?", "?", /* 0x38 - 0x40 */ "?", "?", "?", "?", "?", "?" /* 0x41 - 0x46 */ }; static BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type); static void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id); static void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id); /** * Read RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ BOOL rdp_read_security_header(wStream* s, UINT16* flags, UINT16* length) { /* Basic Security Header */ if ((Stream_GetRemainingLength(s) < 4) || (length && (*length < 4))) return FALSE; Stream_Read_UINT16(s, *flags); /* flags */ Stream_Seek(s, 2); /* flagsHi (unused) */ if (length) *length -= 4; return TRUE; } /** * Write RDP Security Header.\n * @msdn{cc240579} * @param s stream * @param flags security flags */ void rdp_write_security_header(wStream* s, UINT16 flags) { /* Basic Security Header */ Stream_Write_UINT16(s, flags); /* flags */ Stream_Write_UINT16(s, 0); /* flagsHi (unused) */ } BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { UINT16 len; if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, len); /* totalLength */ *length = len; /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (len == 0x8000) { if (!rdp_read_flow_control_pdu(s, type)) return FALSE; *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s))) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (len > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; } void rdp_write_share_control_header(wStream* s, UINT16 length, UINT16 type, UINT16 channel_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; /* Share Control Header */ Stream_Write_UINT16(s, length); /* totalLength */ Stream_Write_UINT16(s, type | 0x10); /* pduType */ Stream_Write_UINT16(s, channel_id); /* pduSource */ } BOOL rdp_read_share_data_header(wStream* s, UINT16* length, BYTE* type, UINT32* shareId, BYTE* compressedType, UINT16* compressedLength) { if (Stream_GetRemainingLength(s) < 12) return FALSE; /* Share Data Header */ Stream_Read_UINT32(s, *shareId); /* shareId (4 bytes) */ Stream_Seek_UINT8(s); /* pad1 (1 byte) */ Stream_Seek_UINT8(s); /* streamId (1 byte) */ Stream_Read_UINT16(s, *length); /* uncompressedLength (2 bytes) */ Stream_Read_UINT8(s, *type); /* pduType2, Data PDU Type (1 byte) */ Stream_Read_UINT8(s, *compressedType); /* compressedType (1 byte) */ Stream_Read_UINT16(s, *compressedLength); /* compressedLength (2 bytes) */ return TRUE; } void rdp_write_share_data_header(wStream* s, UINT16 length, BYTE type, UINT32 share_id) { length -= RDP_PACKET_HEADER_MAX_LENGTH; length -= RDP_SHARE_CONTROL_HEADER_LENGTH; length -= RDP_SHARE_DATA_HEADER_LENGTH; /* Share Data Header */ Stream_Write_UINT32(s, share_id); /* shareId (4 bytes) */ Stream_Write_UINT8(s, 0); /* pad1 (1 byte) */ Stream_Write_UINT8(s, STREAM_LOW); /* streamId (1 byte) */ Stream_Write_UINT16(s, length); /* uncompressedLength (2 bytes) */ Stream_Write_UINT8(s, type); /* pduType2, Data PDU Type (1 byte) */ Stream_Write_UINT8(s, 0); /* compressedType (1 byte) */ Stream_Write_UINT16(s, 0); /* compressedLength (2 bytes) */ } static BOOL rdp_security_stream_init(rdpRdp* rdp, wStream* s, BOOL sec_header) { if (!rdp || !s) return FALSE; if (rdp->do_crypt) { if (!Stream_SafeSeek(s, 12)) return FALSE; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { if (!Stream_SafeSeek(s, 4)) return FALSE; } rdp->sec_flags |= SEC_ENCRYPT; if (rdp->do_secure_checksum) rdp->sec_flags |= SEC_SECURE_CHECKSUM; } else if (rdp->sec_flags != 0 || sec_header) { if (!Stream_SafeSeek(s, 4)) return FALSE; } return TRUE; } wStream* rdp_send_stream_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, FALSE)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_send_stream_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_CONTROL_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } wStream* rdp_data_pdu_init(rdpRdp* rdp) { wStream* s = rdp_send_stream_pdu_init(rdp); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_SHARE_DATA_HEADER_LENGTH)) goto fail; return s; fail: Stream_Release(s); return NULL; } BOOL rdp_set_error_info(rdpRdp* rdp, UINT32 errorInfo) { rdp->errorInfo = errorInfo; if (rdp->errorInfo != ERRINFO_SUCCESS) { rdpContext* context = rdp->context; rdp_print_errinfo(rdp->errorInfo); if (context) { freerdp_set_last_error_log(context, MAKE_FREERDP_ERROR(ERRINFO, errorInfo)); if (context->pubSub) { ErrorInfoEventArgs e; EventArgsInit(&e, "freerdp"); e.code = rdp->errorInfo; PubSub_OnErrorInfo(context->pubSub, context, &e); } } else WLog_ERR(TAG, "%s missing context=%p", __FUNCTION__, context); } else { freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SUCCESS); } return TRUE; } wStream* rdp_message_channel_pdu_init(rdpRdp* rdp) { wStream* s = transport_send_stream_init(rdp->transport, 4096); if (!s) return NULL; if (!Stream_SafeSeek(s, RDP_PACKET_HEADER_MAX_LENGTH)) goto fail; if (!rdp_security_stream_init(rdp, s, TRUE)) goto fail; return s; fail: Stream_Release(s); return NULL; } /** * Read an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ BOOL rdp_read_header(rdpRdp* rdp, wStream* s, UINT16* length, UINT16* channelId) { BYTE li; BYTE byte; BYTE code; BYTE choice; UINT16 initiator; enum DomainMCSPDU MCSPDU; enum DomainMCSPDU domainMCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataRequest : DomainMCSPDU_SendDataIndication; if (!tpkt_read_header(s, length)) return FALSE; if (!tpdu_read_header(s, &code, &li, *length)) return FALSE; if (code != X224_TPDU_DATA) { if (code == X224_TPDU_DISCONNECT_REQUEST) { freerdp_abort_connect(rdp->instance); return TRUE; } return FALSE; } if (!per_read_choice(s, &choice)) return FALSE; domainMCSPDU = (enum DomainMCSPDU)(choice >> 2); if (domainMCSPDU != MCSPDU) { if (domainMCSPDU != DomainMCSPDU_DisconnectProviderUltimatum) return FALSE; } MCSPDU = domainMCSPDU; if (*length < 8U) return FALSE; if ((*length - 8U) > Stream_GetRemainingLength(s)) return FALSE; if (MCSPDU == DomainMCSPDU_DisconnectProviderUltimatum) { int reason = 0; TerminateEventArgs e; rdpContext* context; if (!mcs_recv_disconnect_provider_ultimatum(rdp->mcs, s, &reason)) return FALSE; if (!rdp->instance) return FALSE; context = rdp->instance->context; context->disconnectUltimatum = reason; if (rdp->errorInfo == ERRINFO_SUCCESS) { /** * Some servers like Windows Server 2008 R2 do not send the error info pdu * when the user logs off like they should. Map DisconnectProviderUltimatum * to a ERRINFO_LOGOFF_BY_USER when the errinfo code is ERRINFO_SUCCESS. */ if (reason == Disconnect_Ultimatum_provider_initiated) rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); else if (reason == Disconnect_Ultimatum_user_requested) rdp_set_error_info(rdp, ERRINFO_LOGOFF_BY_USER); else rdp_set_error_info(rdp, ERRINFO_RPC_INITIATED_DISCONNECT); } WLog_DBG(TAG, "DisconnectProviderUltimatum: reason: %d", reason); freerdp_abort_connect(rdp->instance); EventArgsInit(&e, "freerdp"); e.code = 0; PubSub_OnTerminate(context->pubSub, context, &e); return TRUE; } if (Stream_GetRemainingLength(s) < 5) return FALSE; if (!per_read_integer16(s, &initiator, MCS_BASE_CHANNEL_ID)) /* initiator (UserId) */ return FALSE; if (!per_read_integer16(s, channelId, 0)) /* channelId */ return FALSE; Stream_Read_UINT8(s, byte); /* dataPriority + Segmentation (0x70) */ if (!per_read_length(s, length)) /* userData (OCTET_STRING) */ return FALSE; if (*length > Stream_GetRemainingLength(s)) return FALSE; return TRUE; } /** * Write an RDP packet header.\n * @param rdp rdp module * @param s stream * @param length RDP packet length * @param channel_id channel id */ void rdp_write_header(rdpRdp* rdp, wStream* s, UINT16 length, UINT16 channelId) { int body_length; enum DomainMCSPDU MCSPDU; MCSPDU = (rdp->settings->ServerMode) ? DomainMCSPDU_SendDataIndication : DomainMCSPDU_SendDataRequest; if ((rdp->sec_flags & SEC_ENCRYPT) && (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)) { int pad; body_length = length - RDP_PACKET_HEADER_MAX_LENGTH - 16; pad = 8 - (body_length % 8); if (pad != 8) length += pad; } mcs_write_domain_mcspdu_header(s, MCSPDU, length, 0); per_write_integer16(s, rdp->mcs->userId, MCS_BASE_CHANNEL_ID); /* initiator */ per_write_integer16(s, channelId, 0); /* channelId */ Stream_Write_UINT8(s, 0x70); /* dataPriority + segmentation */ /* * We always encode length in two bytes, even though we could use * only one byte if length <= 0x7F. It is just easier that way, * because we can leave room for fixed-length header, store all * the data first and then store the header. */ length = (length - RDP_PACKET_HEADER_MAX_LENGTH) | 0x8000; Stream_Write_UINT16_BE(s, length); /* userData (OCTET_STRING) */ } static BOOL rdp_security_stream_out(rdpRdp* rdp, wStream* s, int length, UINT32 sec_flags, UINT32* pad) { BYTE* data; BOOL status; sec_flags |= rdp->sec_flags; *pad = 0; if (sec_flags != 0) { rdp_write_security_header(s, sec_flags); if (sec_flags & SEC_ENCRYPT) { if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { data = Stream_Pointer(s) + 12; length = length - (data - Stream_Buffer(s)); Stream_Write_UINT16(s, 0x10); /* length */ Stream_Write_UINT8(s, 0x1); /* TSFIPS_VERSION 1*/ /* handle padding */ *pad = 8 - (length % 8); if (*pad == 8) *pad = 0; if (*pad) memset(data + length, 0, *pad); Stream_Write_UINT8(s, *pad); if (!security_hmac_signature(data, length, Stream_Pointer(s), rdp)) return FALSE; Stream_Seek(s, 8); security_fips_encrypt(data, length + *pad, rdp); } else { data = Stream_Pointer(s) + 8; length = length - (data - Stream_Buffer(s)); if (sec_flags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, data, length, TRUE, Stream_Pointer(s)); else status = security_mac_signature(rdp, data, length, Stream_Pointer(s)); if (!status) return FALSE; Stream_Seek(s, 8); if (!security_encrypt(Stream_Pointer(s), length, rdp)) return FALSE; } } rdp->sec_flags = 0; } return TRUE; } static UINT32 rdp_get_sec_bytes(rdpRdp* rdp, UINT16 sec_flags) { UINT32 sec_bytes; if (rdp->sec_flags & SEC_ENCRYPT) { sec_bytes = 12; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) sec_bytes += 4; } else if (rdp->sec_flags != 0 || sec_flags != 0) { sec_bytes = 4; } else { sec_bytes = 0; } return sec_bytes; } /** * Send an RDP packet. * @param rdp RDP module * @param s stream * @param channel_id channel id */ BOOL rdp_send(rdpRdp* rdp, wStream* s, UINT16 channel_id) { BOOL rc = FALSE; UINT32 pad; UINT16 length; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, channel_id); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_pdu(rdpRdp* rdp, wStream* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!rdp || !s) return FALSE; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) return FALSE; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } BOOL rdp_send_data_pdu(rdpRdp* rdp, wStream* s, BYTE type, UINT16 channel_id) { BOOL rc = FALSE; size_t length; UINT32 sec_bytes; size_t sec_hold; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp, 0); sec_hold = Stream_GetPosition(s); Stream_Seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, PDU_TYPE_DATA, channel_id); rdp_write_share_data_header(s, length - sec_bytes, type, rdp->settings->ShareId); Stream_SetPosition(s, sec_hold); if (!rdp_security_stream_out(rdp, s, length, 0, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); WLog_DBG(TAG, "%s: sending data (type=0x%x size=%" PRIuz " channelId=%" PRIu16 ")", __FUNCTION__, type, Stream_Length(s), channel_id); rdp->outPackets++; if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } BOOL rdp_send_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 sec_flags) { BOOL rc = FALSE; UINT16 length; UINT32 pad; if (!s) return FALSE; if (!rdp) goto fail; length = Stream_GetPosition(s); Stream_SetPosition(s, 0); rdp_write_header(rdp, s, length, rdp->mcs->messageChannelId); if (!rdp_security_stream_out(rdp, s, length, sec_flags, &pad)) goto fail; length += pad; Stream_SetPosition(s, length); Stream_SealLength(s); if (transport_write(rdp->transport, s) < 0) goto fail; rc = TRUE; fail: Stream_Release(s); return rc; } static BOOL rdp_recv_server_shutdown_denied_pdu(rdpRdp* rdp, wStream* s) { return TRUE; } static BOOL rdp_recv_server_set_keyboard_indicators_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT16 ledFlags; rdpContext* context = rdp->instance->context; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT16(s, ledFlags); /* ledFlags (2 bytes) */ IFCALL(context->update->SetKeyboardIndicators, context, ledFlags); return TRUE; } static BOOL rdp_recv_server_set_keyboard_ime_status_pdu(rdpRdp* rdp, wStream* s) { UINT16 unitId; UINT32 imeState; UINT32 imeConvMode; if (!rdp || !rdp->input) return FALSE; if (Stream_GetRemainingLength(s) < 10) return FALSE; Stream_Read_UINT16(s, unitId); /* unitId (2 bytes) */ Stream_Read_UINT32(s, imeState); /* imeState (4 bytes) */ Stream_Read_UINT32(s, imeConvMode); /* imeConvMode (4 bytes) */ IFCALL(rdp->update->SetKeyboardImeStatus, rdp->context, unitId, imeState, imeConvMode); return TRUE; } static BOOL rdp_recv_set_error_info_data_pdu(rdpRdp* rdp, wStream* s) { UINT32 errorInfo; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, errorInfo); /* errorInfo (4 bytes) */ return rdp_set_error_info(rdp, errorInfo); } static BOOL rdp_recv_server_auto_reconnect_status_pdu(rdpRdp* rdp, wStream* s) { UINT32 arcStatus; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, arcStatus); /* arcStatus (4 bytes) */ WLog_WARN(TAG, "AutoReconnectStatus: 0x%08" PRIX32 "", arcStatus); return TRUE; } static BOOL rdp_recv_server_status_info_pdu(rdpRdp* rdp, wStream* s) { UINT32 statusCode; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, statusCode); /* statusCode (4 bytes) */ if (rdp->update->ServerStatusInfo) return rdp->update->ServerStatusInfo(rdp->context, statusCode); return TRUE; } static BOOL rdp_recv_monitor_layout_pdu(rdpRdp* rdp, wStream* s) { UINT32 index; UINT32 monitorCount; MONITOR_DEF* monitor; MONITOR_DEF* monitorDefArray; BOOL ret = TRUE; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, monitorCount); /* monitorCount (4 bytes) */ if ((Stream_GetRemainingLength(s) / 20) < monitorCount) return FALSE; monitorDefArray = (MONITOR_DEF*)calloc(monitorCount, sizeof(MONITOR_DEF)); if (!monitorDefArray) return FALSE; for (monitor = monitorDefArray, index = 0; index < monitorCount; index++, monitor++) { Stream_Read_UINT32(s, monitor->left); /* left (4 bytes) */ Stream_Read_UINT32(s, monitor->top); /* top (4 bytes) */ Stream_Read_UINT32(s, monitor->right); /* right (4 bytes) */ Stream_Read_UINT32(s, monitor->bottom); /* bottom (4 bytes) */ Stream_Read_UINT32(s, monitor->flags); /* flags (4 bytes) */ } IFCALLRET(rdp->update->RemoteMonitors, ret, rdp->context, monitorCount, monitorDefArray); free(monitorDefArray); return ret; } int rdp_recv_data_pdu(rdpRdp* rdp, wStream* s) { BYTE type; wStream* cs; UINT16 length; UINT32 shareId; BYTE compressedType; UINT16 compressedLength; if (!rdp_read_share_data_header(s, &length, &type, &shareId, &compressedType, &compressedLength)) { WLog_ERR(TAG, "rdp_read_share_data_header() failed"); return -1; } cs = s; if (compressedType & PACKET_COMPRESSED) { UINT32 DstSize = 0; BYTE* pDstData = NULL; UINT16 SrcSize = compressedLength - 18; if ((compressedLength < 18) || (Stream_GetRemainingLength(s) < SrcSize)) { WLog_ERR(TAG, "bulk_decompress: not enough bytes for compressedLength %" PRIu16 "", compressedLength); return -1; } if (bulk_decompress(rdp->bulk, Stream_Pointer(s), SrcSize, &pDstData, &DstSize, compressedType)) { if (!(cs = StreamPool_Take(rdp->transport->ReceivePool, DstSize))) { WLog_ERR(TAG, "Couldn't take stream from pool"); return -1; } Stream_SetPosition(cs, 0); Stream_Write(cs, pDstData, DstSize); Stream_SealLength(cs); Stream_SetPosition(cs, 0); } else { WLog_ERR(TAG, "bulk_decompress() failed"); return -1; } Stream_Seek(s, SrcSize); } WLog_DBG(TAG, "recv %s Data PDU (0x%02" PRIX8 "), length: %" PRIu16 "", type < ARRAYSIZE(DATA_PDU_TYPE_STRINGS) ? DATA_PDU_TYPE_STRINGS[type] : "???", type, length); switch (type) { case DATA_PDU_TYPE_UPDATE: if (!update_recv(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_UPDATE - update_recv() failed"); goto out_fail; } break; case DATA_PDU_TYPE_CONTROL: if (!rdp_recv_server_control_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_CONTROL - rdp_recv_server_control_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_POINTER: if (!update_recv_pointer(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_POINTER - update_recv_pointer() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SYNCHRONIZE: if (!rdp_recv_synchronize_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SYNCHRONIZE - rdp_recv_synchronize_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_PLAY_SOUND: if (!update_recv_play_sound(rdp->update, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_PLAY_SOUND - update_recv_play_sound() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SHUTDOWN_DENIED: if (!rdp_recv_server_shutdown_denied_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SHUTDOWN_DENIED - rdp_recv_server_shutdown_denied_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SAVE_SESSION_INFO: if (!rdp_recv_save_session_info(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SAVE_SESSION_INFO - rdp_recv_save_session_info() failed"); goto out_fail; } break; case DATA_PDU_TYPE_FONT_MAP: if (!rdp_recv_font_map_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_FONT_MAP - rdp_recv_font_map_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS: if (!rdp_recv_server_set_keyboard_indicators_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS - " "rdp_recv_server_set_keyboard_indicators_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS: if (!rdp_recv_server_set_keyboard_ime_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS - " "rdp_recv_server_set_keyboard_ime_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_SET_ERROR_INFO: if (!rdp_recv_set_error_info_data_pdu(rdp, cs)) { WLog_ERR( TAG, "DATA_PDU_TYPE_SET_ERROR_INFO - rdp_recv_set_error_info_data_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_ARC_STATUS: if (!rdp_recv_server_auto_reconnect_status_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_ARC_STATUS - " "rdp_recv_server_auto_reconnect_status_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_STATUS_INFO: if (!rdp_recv_server_status_info_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_STATUS_INFO - rdp_recv_server_status_info_pdu() failed"); goto out_fail; } break; case DATA_PDU_TYPE_MONITOR_LAYOUT: if (!rdp_recv_monitor_layout_pdu(rdp, cs)) { WLog_ERR(TAG, "DATA_PDU_TYPE_MONITOR_LAYOUT - rdp_recv_monitor_layout_pdu() failed"); goto out_fail; } break; default: break; } if (cs != s) Stream_Release(cs); return 0; out_fail: if (cs != s) Stream_Release(cs); return -1; } int rdp_recv_message_channel_pdu(rdpRdp* rdp, wStream* s, UINT16 securityFlags) { if (securityFlags & SEC_AUTODETECT_REQ) { /* Server Auto-Detect Request PDU */ return rdp_recv_autodetect_request_packet(rdp, s); } if (securityFlags & SEC_AUTODETECT_RSP) { /* Client Auto-Detect Response PDU */ return rdp_recv_autodetect_response_packet(rdp, s); } if (securityFlags & SEC_HEARTBEAT) { /* Heartbeat PDU */ return rdp_recv_heartbeat_packet(rdp, s); } if (securityFlags & SEC_TRANSPORT_REQ) { /* Initiate Multitransport Request PDU */ return rdp_recv_multitransport_packet(rdp, s); } return -1; } int rdp_recv_out_of_sequence_pdu(rdpRdp* rdp, wStream* s) { UINT16 type; UINT16 length; UINT16 channelId; if (!rdp_read_share_control_header(s, &length, &type, &channelId)) return -1; if (type == PDU_TYPE_DATA) { return rdp_recv_data_pdu(rdp, s); } else if (type == PDU_TYPE_SERVER_REDIRECTION) { return rdp_recv_enhanced_security_redirection_packet(rdp, s); } else if (type == PDU_TYPE_FLOW_RESPONSE || type == PDU_TYPE_FLOW_STOP || type == PDU_TYPE_FLOW_TEST) { return 0; } else { return -1; } } BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; if (!type) return FALSE; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ return TRUE; } /** * Decrypt an RDP packet.\n * @param rdp RDP module * @param s stream * @param length int */ BOOL rdp_decrypt(rdpRdp* rdp, wStream* s, UINT16* pLength, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; BOOL status; INT32 length; if (!rdp || !s || !pLength) return FALSE; length = *pLength; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; INT64 padLength; if (Stream_GetRemainingLength(s) < 12) return FALSE; Stream_Read_UINT16(s, len); /* 0x10 */ Stream_Read_UINT8(s, version); /* 0x1 */ Stream_Read_UINT8(s, pad); sig = Stream_Pointer(s); Stream_Seek(s, 8); /* signature */ length -= 12; padLength = length - pad; if ((length <= 0) || (padLength <= 0)) return FALSE; if (!security_fips_decrypt(Stream_Pointer(s), length, rdp)) { WLog_ERR(TAG, "FATAL: cannot decrypt"); return FALSE; /* TODO */ } if (!security_fips_check_signature(Stream_Pointer(s), length - pad, sig, rdp)) { WLog_ERR(TAG, "FATAL: invalid packet signature"); return FALSE; /* TODO */ } Stream_SetLength(s, Stream_Length(s) - pad); *pLength = padLength; return TRUE; } if (Stream_GetRemainingLength(s) < sizeof(wmac)) return FALSE; Stream_Read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (length <= 0) return FALSE; if (!security_decrypt(Stream_Pointer(s), length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) status = security_salted_mac_signature(rdp, Stream_Pointer(s), length, FALSE, cmac); else status = security_mac_signature(rdp, Stream_Pointer(s), length, cmac); if (!status) return FALSE; if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { WLog_ERR(TAG, "WARNING: invalid packet signature"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ // return FALSE; } *pLength = length; return TRUE; } static const char* pdu_type_to_str(UINT16 pduType) { static char buffer[1024] = { 0 }; switch (pduType) { case PDU_TYPE_DEMAND_ACTIVE: return "PDU_TYPE_DEMAND_ACTIVE"; case PDU_TYPE_CONFIRM_ACTIVE: return "PDU_TYPE_CONFIRM_ACTIVE"; case PDU_TYPE_DEACTIVATE_ALL: return "PDU_TYPE_DEACTIVATE_ALL"; case PDU_TYPE_DATA: return "PDU_TYPE_DATA"; case PDU_TYPE_SERVER_REDIRECTION: return "PDU_TYPE_SERVER_REDIRECTION"; case PDU_TYPE_FLOW_TEST: return "PDU_TYPE_FLOW_TEST"; case PDU_TYPE_FLOW_RESPONSE: return "PDU_TYPE_FLOW_RESPONSE"; case PDU_TYPE_FLOW_STOP: return "PDU_TYPE_FLOW_STOP"; default: _snprintf(buffer, sizeof(buffer), "UNKNOWN %04" PRIx16, pduType); return buffer; } } /** * Process an RDP packet.\n * @param rdp RDP module * @param s stream */ static int rdp_recv_tpkt_pdu(rdpRdp* rdp, wStream* s) { int rc = 0; UINT16 length; UINT16 pduType; UINT16 pduLength; UINT16 pduSource; UINT16 channelId = 0; UINT16 securityFlags = 0; if (!rdp_read_header(rdp, s, &length, &channelId)) { WLog_ERR(TAG, "Incorrect RDP header."); return -1; } if (freerdp_shall_disconnect(rdp->instance)) return 0; if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (rdp->settings->UseRdpSecurityLayer) { if (!rdp_read_security_header(s, &securityFlags, &length)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_security_header() fail"); return -1; } if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT)) { if (!rdp_decrypt(rdp, s, &length, securityFlags)) { WLog_ERR(TAG, "rdp_decrypt failed"); return -1; } } if (securityFlags & SEC_REDIRECTION_PKT) { /* * [MS-RDPBCGR] 2.2.13.2.1 * - no share control header, nor the 2 byte pad */ Stream_Rewind(s, 2); rdp->inPackets++; rc = rdp_recv_enhanced_security_redirection_packet(rdp, s); goto out; } } if (channelId == MCS_GLOBAL_CHANNEL_ID) { while (Stream_GetRemainingLength(s) > 3) { size_t startheader, endheader, start, end, diff, headerdiff; startheader = Stream_GetPosition(s); if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() fail"); return -1; } start = endheader = Stream_GetPosition(s); headerdiff = endheader - startheader; if (pduLength < headerdiff) { WLog_ERR( TAG, "rdp_recv_tpkt_pdu: rdp_read_share_control_header() invalid pduLength %" PRIu16, pduLength); return -1; } pduLength -= headerdiff; rdp->settings->PduSource = pduSource; rdp->inPackets++; switch (pduType) { case PDU_TYPE_DATA: rc = rdp_recv_data_pdu(rdp, s); if (rc < 0) return rc; break; case PDU_TYPE_DEACTIVATE_ALL: if (!rdp_recv_deactivate_all(rdp, s)) { WLog_ERR(TAG, "rdp_recv_tpkt_pdu: rdp_recv_deactivate_all() fail"); return -1; } break; case PDU_TYPE_SERVER_REDIRECTION: return rdp_recv_enhanced_security_redirection_packet(rdp, s); case PDU_TYPE_FLOW_RESPONSE: case PDU_TYPE_FLOW_STOP: case PDU_TYPE_FLOW_TEST: WLog_DBG(TAG, "flow message 0x%04" PRIX16 "", pduType); /* http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (!Stream_SafeSeek(s, pduLength)) return -1; break; default: WLog_ERR(TAG, "incorrect PDU type: 0x%04" PRIX16 "", pduType); break; } end = Stream_GetPosition(s); diff = end - start; if (diff != pduLength) { WLog_WARN(TAG, "pduType %s not properly parsed, %" PRIdz " bytes remaining unhandled. Skipping.", pdu_type_to_str(pduType), diff); if (!Stream_SafeSeek(s, pduLength)) return -1; } } } else if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId)) { if (!rdp->settings->UseRdpSecurityLayer) if (!rdp_read_security_header(s, &securityFlags, NULL)) return -1; rdp->inPackets++; rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags); } else { rdp->inPackets++; if (!freerdp_channel_process(rdp->instance, s, channelId, length)) return -1; } out: if (!tpkt_ensure_stream_consumed(s, length)) return -1; return rc; } static int rdp_recv_fastpath_pdu(rdpRdp* rdp, wStream* s) { UINT16 length; rdpFastPath* fastpath; fastpath = rdp->fastpath; if (!fastpath_read_header_rdp(fastpath, s, &length)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: fastpath_read_header_rdp() fail"); return -1; } if ((length == 0) || (length > Stream_GetRemainingLength(s))) { WLog_ERR(TAG, "incorrect FastPath PDU header length %" PRIu16 "", length); return -1; } if (rdp->autodetect->bandwidthMeasureStarted) { rdp->autodetect->bandwidthMeasureByteCount += length; } if (fastpath->encryptionFlags & FASTPATH_OUTPUT_ENCRYPTED) { UINT16 flags = (fastpath->encryptionFlags & FASTPATH_OUTPUT_SECURE_CHECKSUM) ? SEC_SECURE_CHECKSUM : 0; if (!rdp_decrypt(rdp, s, &length, flags)) { WLog_ERR(TAG, "rdp_recv_fastpath_pdu: rdp_decrypt() fail"); return -1; } } return fastpath_recv_updates(rdp->fastpath, s); } static int rdp_recv_pdu(rdpRdp* rdp, wStream* s) { if (tpkt_verify_header(s)) return rdp_recv_tpkt_pdu(rdp, s); else return rdp_recv_fastpath_pdu(rdp, s); } int rdp_recv_callback(rdpTransport* transport, wStream* s, void* extra) { int status = 0; rdpRdp* rdp = (rdpRdp*)extra; /* * At any point in the connection sequence between when all * MCS channels have been joined and when the RDP connection * enters the active state, an auto-detect PDU can be received * on the MCS message channel. */ if ((rdp->state > CONNECTION_STATE_MCS_CHANNEL_JOIN) && (rdp->state < CONNECTION_STATE_ACTIVE)) { if (rdp_client_connect_auto_detect(rdp, s)) return 0; } switch (rdp->state) { case CONNECTION_STATE_NLA: if (nla_get_state(rdp->nla) < NLA_STATE_AUTH_INFO) { if (nla_recv_pdu(rdp->nla, s) < 1) { WLog_ERR(TAG, "%s: %s - nla_recv_pdu() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } else if (nla_get_state(rdp->nla) == NLA_STATE_POST_NEGO) { nego_recv(rdp->transport, s, (void*)rdp->nego); if (nego_get_state(rdp->nego) != NEGO_STATE_FINAL) { WLog_ERR(TAG, "%s: %s - nego_recv() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } if (nla_get_state(rdp->nla) == NLA_STATE_AUTH_INFO) { transport_set_nla_mode(rdp->transport, FALSE); if (rdp->settings->VmConnectMode) { if (!nego_set_state(rdp->nego, NEGO_STATE_NLA)) return -1; if (!nego_set_requested_protocols(rdp->nego, PROTOCOL_HYBRID | PROTOCOL_SSL)) return -1; nego_send_negotiation_request(rdp->nego); if (!nla_set_state(rdp->nla, NLA_STATE_POST_NEGO)) return -1; } else { if (!nla_set_state(rdp->nla, NLA_STATE_FINAL)) return -1; } } if (nla_get_state(rdp->nla) == NLA_STATE_FINAL) { nla_free(rdp->nla); rdp->nla = NULL; if (!mcs_client_begin(rdp->mcs)) { WLog_ERR(TAG, "%s: %s - mcs_client_begin() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); return -1; } } break; case CONNECTION_STATE_MCS_CONNECT: if (!mcs_recv_connect_response(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_connect_response failure"); return -1; } if (!mcs_send_erect_domain_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_erect_domain_request failure"); return -1; } if (!mcs_send_attach_user_request(rdp->mcs)) { WLog_ERR(TAG, "mcs_send_attach_user_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER); break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!mcs_recv_attach_user_confirm(rdp->mcs, s)) { WLog_ERR(TAG, "mcs_recv_attach_user_confirm failure"); return -1; } if (!mcs_send_channel_join_request(rdp->mcs, rdp->mcs->userId)) { WLog_ERR(TAG, "mcs_send_channel_join_request failure"); return -1; } rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN); break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (!rdp_client_connect_mcs_channel_join_confirm(rdp, s)) { WLog_ERR(TAG, "%s: %s - " "rdp_client_connect_mcs_channel_join_confirm() fail", __FUNCTION__, rdp_server_connection_state_string(rdp->state)); status = -1; } break; case CONNECTION_STATE_LICENSING: status = rdp_client_connect_license(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_client_connect_license() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_CAPABILITIES_EXCHANGE: status = rdp_client_connect_demand_active(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - " "rdp_client_connect_demand_active() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_FINALIZATION: status = rdp_recv_pdu(rdp, s); if ((status >= 0) && (rdp->finalize_sc_pdus == FINALIZE_SC_COMPLETE)) { ActivatedEventArgs activatedEvent; rdpContext* context = rdp->context; rdp_client_transition_to_state(rdp, CONNECTION_STATE_ACTIVE); EventArgsInit(&activatedEvent, "libfreerdp"); activatedEvent.firstActivation = !rdp->deactivation_reactivation; PubSub_OnActivated(context->pubSub, context, &activatedEvent); return 2; } if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; case CONNECTION_STATE_ACTIVE: status = rdp_recv_pdu(rdp, s); if (status < 0) WLog_DBG(TAG, "%s: %s - rdp_recv_pdu() - %i", __FUNCTION__, rdp_server_connection_state_string(rdp->state), status); break; default: WLog_ERR(TAG, "%s: %s state %d", __FUNCTION__, rdp_server_connection_state_string(rdp->state), rdp->state); status = -1; break; } return status; } BOOL rdp_send_channel_data(rdpRdp* rdp, UINT16 channelId, const BYTE* data, size_t size) { return freerdp_channel_send(rdp, channelId, data, size); } BOOL rdp_send_error_info(rdpRdp* rdp) { wStream* s; BOOL status; if (rdp->errorInfo == ERRINFO_SUCCESS) return TRUE; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, rdp->errorInfo); /* error id (4 bytes) */ status = rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_ERROR_INFO, 0); return status; } int rdp_check_fds(rdpRdp* rdp) { int status; rdpTransport* transport = rdp->transport; if (transport->tsg) { rdpTsg* tsg = transport->tsg; if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "rdp_check_fds: tsg_check_event_handles()"); return -1; } if (tsg_get_state(tsg) != TSG_STATE_PIPE_CREATED) return 1; } status = transport_check_fds(transport); if (status == 1) { if (!rdp_client_redirect(rdp)) /* session redirection */ return -1; } if (status < 0) WLog_DBG(TAG, "transport_check_fds() - %i", status); return status; } BOOL freerdp_get_stats(rdpRdp* rdp, UINT64* inBytes, UINT64* outBytes, UINT64* inPackets, UINT64* outPackets) { if (!rdp) return FALSE; if (inBytes) *inBytes = rdp->inBytes; if (outBytes) *outBytes = rdp->outBytes; if (inPackets) *inPackets = rdp->inPackets; if (outPackets) *outPackets = rdp->outPackets; return TRUE; } /** * Instantiate new RDP module. * @return new RDP module */ rdpRdp* rdp_new(rdpContext* context) { rdpRdp* rdp; DWORD flags; BOOL newSettings = FALSE; rdp = (rdpRdp*)calloc(1, sizeof(rdpRdp)); if (!rdp) return NULL; rdp->context = context; rdp->instance = context->instance; flags = 0; if (context->ServerMode) flags |= FREERDP_SETTINGS_SERVER_MODE; if (!context->settings) { context->settings = freerdp_settings_new(flags); if (!context->settings) goto out_free; newSettings = TRUE; } rdp->settings = context->settings; if (context->instance) { rdp->settings->instance = context->instance; context->instance->settings = rdp->settings; } else if (context->peer) { rdp->settings->instance = context->peer; context->peer->settings = rdp->settings; } rdp->transport = transport_new(context); if (!rdp->transport) goto out_free_settings; rdp->license = license_new(rdp); if (!rdp->license) goto out_free_transport; rdp->input = input_new(rdp); if (!rdp->input) goto out_free_license; rdp->update = update_new(rdp); if (!rdp->update) goto out_free_input; rdp->fastpath = fastpath_new(rdp); if (!rdp->fastpath) goto out_free_update; rdp->nego = nego_new(rdp->transport); if (!rdp->nego) goto out_free_fastpath; rdp->mcs = mcs_new(rdp->transport); if (!rdp->mcs) goto out_free_nego; rdp->redirection = redirection_new(); if (!rdp->redirection) goto out_free_mcs; rdp->autodetect = autodetect_new(); if (!rdp->autodetect) goto out_free_redirection; rdp->heartbeat = heartbeat_new(); if (!rdp->heartbeat) goto out_free_autodetect; rdp->multitransport = multitransport_new(); if (!rdp->multitransport) goto out_free_heartbeat; rdp->bulk = bulk_new(context); if (!rdp->bulk) goto out_free_multitransport; return rdp; out_free_multitransport: multitransport_free(rdp->multitransport); out_free_heartbeat: heartbeat_free(rdp->heartbeat); out_free_autodetect: autodetect_free(rdp->autodetect); out_free_redirection: redirection_free(rdp->redirection); out_free_mcs: mcs_free(rdp->mcs); out_free_nego: nego_free(rdp->nego); out_free_fastpath: fastpath_free(rdp->fastpath); out_free_update: update_free(rdp->update); out_free_input: input_free(rdp->input); out_free_license: license_free(rdp->license); out_free_transport: transport_free(rdp->transport); out_free_settings: if (newSettings) freerdp_settings_free(rdp->settings); out_free: free(rdp); return NULL; } void rdp_reset(rdpRdp* rdp) { rdpContext* context; rdpSettings* settings; context = rdp->context; settings = rdp->settings; bulk_reset(rdp->bulk); if (rdp->rc4_decrypt_key) { winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = NULL; } if (rdp->rc4_encrypt_key) { winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = NULL; } if (rdp->fips_encrypt) { winpr_Cipher_Free(rdp->fips_encrypt); rdp->fips_encrypt = NULL; } if (rdp->fips_decrypt) { winpr_Cipher_Free(rdp->fips_decrypt); rdp->fips_decrypt = NULL; } if (settings->ServerRandom) { free(settings->ServerRandom); settings->ServerRandom = NULL; settings->ServerRandomLength = 0; } if (settings->ServerCertificate) { free(settings->ServerCertificate); settings->ServerCertificate = NULL; } if (settings->ClientAddress) { free(settings->ClientAddress); settings->ClientAddress = NULL; } mcs_free(rdp->mcs); nego_free(rdp->nego); license_free(rdp->license); transport_free(rdp->transport); fastpath_free(rdp->fastpath); rdp->transport = transport_new(context); rdp->license = license_new(rdp); rdp->nego = nego_new(rdp->transport); rdp->mcs = mcs_new(rdp->transport); rdp->fastpath = fastpath_new(rdp); rdp->transport->layer = TRANSPORT_LAYER_TCP; rdp->errorInfo = 0; rdp->deactivation_reactivation = 0; rdp->finalize_sc_pdus = 0; } /** * Free RDP module. * @param rdp RDP module to be freed */ void rdp_free(rdpRdp* rdp) { if (rdp) { winpr_RC4_Free(rdp->rc4_decrypt_key); winpr_RC4_Free(rdp->rc4_encrypt_key); winpr_Cipher_Free(rdp->fips_encrypt); winpr_Cipher_Free(rdp->fips_decrypt); freerdp_settings_free(rdp->settings); transport_free(rdp->transport); license_free(rdp->license); input_free(rdp->input); update_free(rdp->update); fastpath_free(rdp->fastpath); nego_free(rdp->nego); mcs_free(rdp->mcs); nla_free(rdp->nla); redirection_free(rdp->redirection); autodetect_free(rdp->autodetect); heartbeat_free(rdp->heartbeat); multitransport_free(rdp->multitransport); bulk_free(rdp->bulk); free(rdp); } }
BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, *length); /* totalLength */ /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (*length == 0x8000) { rdp_read_flow_control_pdu(s, type); *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if (((size_t)*length - 2) > Stream_GetRemainingLength(s)) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (*length > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; }
BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id) { UINT16 len; if (Stream_GetRemainingLength(s) < 2) return FALSE; /* Share Control Header */ Stream_Read_UINT16(s, len); /* totalLength */ *length = len; /* If length is 0x8000 then we actually got a flow control PDU that we should ignore http://msdn.microsoft.com/en-us/library/cc240576.aspx */ if (len == 0x8000) { if (!rdp_read_flow_control_pdu(s, type)) return FALSE; *channel_id = 0; *length = 8; /* Flow control PDU is 8 bytes */ return TRUE; } if ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s))) return FALSE; Stream_Read_UINT16(s, *type); /* pduType */ *type &= 0x0F; /* type is in the 4 least significant bits */ if (len > 4) Stream_Read_UINT16(s, *channel_id); /* pduSource */ else *channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */ return TRUE; }
{'added': [(105, 'static BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type);'), (148, '\tUINT16 len;'), (153, '\tStream_Read_UINT16(s, len); /* totalLength */'), (154, ''), (155, '\t*length = len;'), (159, '\tif (len == 0x8000)'), (161, '\t\tif (!rdp_read_flow_control_pdu(s, type))'), (162, '\t\t\treturn FALSE;'), (168, '\tif ((len < 4) || ((len - 2) > Stream_GetRemainingLength(s)))'), (174, '\tif (len > 4)'), (1123, 'BOOL rdp_read_flow_control_pdu(wStream* s, UINT16* type)'), (1133, '\tif (!type)'), (1134, '\t\treturn FALSE;'), (1135, '\tif (Stream_GetRemainingLength(s) < 6)'), (1136, '\t\treturn FALSE;'), (1143, '\treturn TRUE;')], 'deleted': [(105, 'static void rdp_read_flow_control_pdu(wStream* s, UINT16* type);'), (152, '\tStream_Read_UINT16(s, *length); /* totalLength */'), (156, '\tif (*length == 0x8000)'), (158, '\t\trdp_read_flow_control_pdu(s, type);'), (164, '\tif (((size_t)*length - 2) > Stream_GetRemainingLength(s))'), (170, '\tif (*length > 4)'), (1119, 'void rdp_read_flow_control_pdu(wStream* s, UINT16* type)')]}
16
7
1,482
7,621
https://github.com/FreeRDP/FreeRDP
CVE-2020-11048
['CWE-125']
lua_struct.c
controloptions
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } }
static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } }
{'added': [(92, 'static int getnum (lua_State *L, const char **fmt, int df) {'), (98, " if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))"), (99, ' luaL_error(L, "integral size overflow");'), (120, " case 'c': return getnum(L, fmt, 1);"), (122, ' int sz = getnum(L, fmt, sizeof(int));'), (155, ' int a = getnum(L, fmt, MAXALIGN);')], 'deleted': [(92, 'static int getnum (const char **fmt, int df) {'), (118, " case 'c': return getnum(fmt, 1);"), (120, ' int sz = getnum(fmt, sizeof(int));'), (153, ' int a = getnum(fmt, MAXALIGN);')]}
6
4
295
2,041
https://github.com/antirez/redis
CVE-2020-14147
['CWE-190', 'CWE-787']
lua_struct.c
getnum
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } }
static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } }
{'added': [(92, 'static int getnum (lua_State *L, const char **fmt, int df) {'), (98, " if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))"), (99, ' luaL_error(L, "integral size overflow");'), (120, " case 'c': return getnum(L, fmt, 1);"), (122, ' int sz = getnum(L, fmt, sizeof(int));'), (155, ' int a = getnum(L, fmt, MAXALIGN);')], 'deleted': [(92, 'static int getnum (const char **fmt, int df) {'), (118, " case 'c': return getnum(fmt, 1);"), (120, ' int sz = getnum(fmt, sizeof(int));'), (153, ' int a = getnum(fmt, MAXALIGN);')]}
6
4
295
2,041
https://github.com/antirez/redis
CVE-2020-14147
['CWE-190', 'CWE-787']
lua_struct.c
optsize
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } }
static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } }
{'added': [(92, 'static int getnum (lua_State *L, const char **fmt, int df) {'), (98, " if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))"), (99, ' luaL_error(L, "integral size overflow");'), (120, " case 'c': return getnum(L, fmt, 1);"), (122, ' int sz = getnum(L, fmt, sizeof(int));'), (155, ' int a = getnum(L, fmt, MAXALIGN);')], 'deleted': [(92, 'static int getnum (const char **fmt, int df) {'), (118, " case 'c': return getnum(fmt, 1);"), (120, ' int sz = getnum(fmt, sizeof(int));'), (153, ' int a = getnum(fmt, MAXALIGN);')]}
6
4
295
2,041
https://github.com/antirez/redis
CVE-2020-14147
['CWE-190', 'CWE-787']
userfunc.c
define_function
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; }
define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
userfunc.c
ex_function
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); }
ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
userfunc.c
get_function_args
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; }
get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
userfunc.c
get_function_body
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; }
get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
userfunc.c
get_function_line
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; }
get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
userfunc.c
lambda_function_body
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and use "line_to_free" to * handle freeing the line later. */ static char_u * get_function_line( exarg_T *eap, char_u **line_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (*eap->cmdlinep == *line_to_free) *eap->cmdlinep = theline; vim_free(*line_to_free); *line_to_free = theline; } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, char_u **line_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, line_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, char_u **line_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, line_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep". eap->nextcmd = nextcmd; if (*line_to_free != NULL && *eap->cmdlinep != *line_to_free) { vim_free(*eap->cmdlinep); *eap->cmdlinep = *line_to_free; *line_to_free = NULL; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, line_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { char_u *line_to_free = NULL; (void)define_function(eap, NULL, &line_to_free); vim_free(line_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * userfunc.c: User defined function support */ #include "vim.h" #if defined(FEAT_EVAL) || defined(PROTO) /* * All user-defined functions are found in this hashtable. */ static hashtab_T func_hashtab; // Used by get_func_tv() static garray_T funcargs = GA_EMPTY; // pointer to funccal for currently active function static funccall_T *current_funccal = NULL; // Pointer to list of previously used funccal, still around because some // item in it is still being used. static funccall_T *previous_funccal = NULL; static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force); static void func_clear(ufunc_T *fp, int force); static int func_free(ufunc_T *fp, int force); void func_init() { hash_init(&func_hashtab); } #if defined(FEAT_PROFILE) || defined(PROTO) /* * Return the function hash table */ hashtab_T * func_tbl_get(void) { return &func_hashtab; } #endif /* * Get one function argument. * If "argtypes" is not NULL also get the type: "arg: type" (:def function). * If "types_optional" is TRUE a missing type is OK, use "any". * If "evalarg" is not NULL use it to check for an already declared name. * Return a pointer to after the type. * When something is wrong return "arg". */ static char_u * one_function_arg( char_u *arg, garray_T *newargs, garray_T *argtypes, int types_optional, evalarg_T *evalarg, int is_vararg, int skip) { char_u *p = arg; char_u *arg_copy = NULL; int is_underscore = FALSE; while (ASCII_ISALNUM(*p) || *p == '_') ++p; if (arg == p || isdigit(*arg) || (argtypes == NULL && ((p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0) || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0)))) { if (!skip) semsg(_(e_illegal_argument_str), arg); return arg; } // Vim9 script: cannot use script var name for argument. In function: also // check local vars and arguments. if (!skip && argtypes != NULL && check_defined(arg, p - arg, evalarg == NULL ? NULL : evalarg->eval_cctx, TRUE) == FAIL) return arg; if (newargs != NULL && ga_grow(newargs, 1) == FAIL) return arg; if (newargs != NULL) { int c; int i; c = *p; *p = NUL; arg_copy = vim_strsave(arg); if (arg_copy == NULL) { *p = c; return arg; } is_underscore = arg_copy[0] == '_' && arg_copy[1] == NUL; if (argtypes == NULL || !is_underscore) // Check for duplicate argument name. for (i = 0; i < newargs->ga_len; ++i) if (STRCMP(((char_u **)(newargs->ga_data))[i], arg_copy) == 0) { semsg(_(e_duplicate_argument_name_str), arg_copy); vim_free(arg_copy); return arg; } ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg_copy; newargs->ga_len++; *p = c; } // get any type from "arg: type" if (argtypes != NULL && (skip || ga_grow(argtypes, 1) == OK)) { char_u *type = NULL; if (VIM_ISWHITE(*p) && *skipwhite(p) == ':') { semsg(_(e_no_white_space_allowed_before_colon_str), arg_copy == NULL ? arg : arg_copy); p = skipwhite(p); } if (*p == ':') { ++p; if (!skip && !VIM_ISWHITE(*p)) { semsg(_(e_white_space_required_after_str_str), ":", p - 1); return arg; } type = skipwhite(p); p = skip_type(type, TRUE); if (!skip) type = vim_strnsave(type, p - type); } else if (*skipwhite(p) != '=' && !types_optional && !is_underscore) { semsg(_(e_missing_argument_type_for_str), arg_copy == NULL ? arg : arg_copy); return arg; } if (!skip) { if (type == NULL && types_optional) // lambda arguments default to "any" type type = vim_strsave((char_u *) (is_vararg ? "list<any>" : "any")); ((char_u **)argtypes->ga_data)[argtypes->ga_len++] = type; } } return p; } /* * Handle line continuation in function arguments or body. * Get a next line, store it in "eap" if appropriate and put the line in * "lines_to_free" to free the line later. */ static char_u * get_function_line( exarg_T *eap, garray_T *lines_to_free, int indent, getline_opt_T getline_options) { char_u *theline; if (eap->getline == NULL) theline = getcmdline(':', 0L, indent, 0); else theline = eap->getline(':', eap->cookie, indent, getline_options); if (theline != NULL) { if (lines_to_free->ga_len > 0 && *eap->cmdlinep == ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) *eap->cmdlinep = theline; ga_add_string(lines_to_free, theline); } return theline; } /* * Get function arguments. * "argp" should point to just after the "(", possibly to white space. * "argp" is advanced just after "endchar". */ static int get_function_args( char_u **argp, char_u endchar, garray_T *newargs, garray_T *argtypes, // NULL unless using :def int types_optional, // types optional if "argtypes" is not NULL evalarg_T *evalarg, // context or NULL int *varargs, garray_T *default_args, int skip, exarg_T *eap, garray_T *lines_to_free) { int mustend = FALSE; char_u *arg; char_u *p; int c; int any_default = FALSE; char_u *expr; char_u *whitep = *argp; if (newargs != NULL) ga_init2(newargs, (int)sizeof(char_u *), 3); if (argtypes != NULL) ga_init2(argtypes, (int)sizeof(char_u *), 3); if (!skip && default_args != NULL) ga_init2(default_args, (int)sizeof(char_u *), 3); if (varargs != NULL) *varargs = FALSE; /* * Isolate the arguments: "arg1, arg2, ...)" */ arg = skipwhite(*argp); p = arg; while (*p != endchar) { while (eap != NULL && eap->getline != NULL && (*p == NUL || (VIM_ISWHITE(*whitep) && *p == '#'))) { // End of the line, get the next one. char_u *theline = get_function_line(eap, lines_to_free, 0, GETLINE_CONCAT_CONT); if (theline == NULL) break; whitep = (char_u *)" "; p = skipwhite(theline); } if (mustend && *p != endchar) { if (!skip) semsg(_(e_invalid_argument_str), *argp); goto err_ret; } if (*p == endchar) break; if (p[0] == '.' && p[1] == '.' && p[2] == '.') { if (varargs != NULL) *varargs = TRUE; p += 3; mustend = TRUE; if (argtypes != NULL) { // ...name: list<type> if (!eval_isnamec1(*p)) { if (!skip) emsg(_(e_missing_name_after_dots)); goto err_ret; } arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, TRUE, skip); if (p == arg) break; if (*skipwhite(p) == '=') { emsg(_(e_cannot_use_default_for_variable_arguments)); break; } } } else { char_u *np; arg = p; p = one_function_arg(p, newargs, argtypes, types_optional, evalarg, FALSE, skip); if (p == arg) break; // Recognize " = expr" but not " == expr". A lambda can have // "(a = expr" but "(a == expr" and "(a =~ expr" are not a lambda. np = skipwhite(p); if (*np == '=' && np[1] != '=' && np[1] != '~' && default_args != NULL) { typval_T rettv; // find the end of the expression (doesn't evaluate it) any_default = TRUE; p = skipwhite(p) + 1; whitep = p; p = skipwhite(p); expr = p; if (eval1(&p, &rettv, NULL) != FAIL) { if (!skip) { if (ga_grow(default_args, 1) == FAIL) goto err_ret; // trim trailing whitespace while (p > expr && VIM_ISWHITE(p[-1])) p--; c = *p; *p = NUL; expr = vim_strsave(expr); if (expr == NULL) { *p = c; goto err_ret; } ((char_u **)(default_args->ga_data)) [default_args->ga_len] = expr; default_args->ga_len++; *p = c; } } else mustend = TRUE; } else if (any_default) { emsg(_(e_non_default_argument_follows_default_argument)); goto err_ret; } if (VIM_ISWHITE(*p) && *skipwhite(p) == ',') { // Be tolerant when skipping if (!skip) { semsg(_(e_no_white_space_allowed_before_str_str), ",", p); goto err_ret; } p = skipwhite(p); } if (*p == ',') { ++p; // Don't give this error when skipping, it makes the "->" not // found in "{k,v -> x}" and give a confusing error. // Allow missing space after comma in legacy functions. if (!skip && argtypes != NULL && !IS_WHITE_OR_NUL(*p) && *p != endchar) { semsg(_(e_white_space_required_after_str_str), ",", p - 1); goto err_ret; } } else mustend = TRUE; } whitep = p; p = skipwhite(p); } if (*p != endchar) goto err_ret; ++p; // skip "endchar" *argp = p; return OK; err_ret: if (newargs != NULL) ga_clear_strings(newargs); if (!skip && default_args != NULL) ga_clear_strings(default_args); return FAIL; } /* * Parse the argument types, filling "fp->uf_arg_types". * Return OK or FAIL. */ static int parse_argument_types(ufunc_T *fp, garray_T *argtypes, int varargs) { int len = 0; ga_init2(&fp->uf_type_list, sizeof(type_T *), 10); if (argtypes->ga_len > 0) { // When "varargs" is set the last name/type goes into uf_va_name // and uf_va_type. len = argtypes->ga_len - (varargs ? 1 : 0); if (len > 0) fp->uf_arg_types = ALLOC_CLEAR_MULT(type_T *, len); if (fp->uf_arg_types != NULL) { int i; type_T *type; for (i = 0; i < len; ++ i) { char_u *p = ((char_u **)argtypes->ga_data)[i]; if (p == NULL) // will get the type from the default value type = &t_unknown; else type = parse_type(&p, &fp->uf_type_list, TRUE); if (type == NULL) return FAIL; fp->uf_arg_types[i] = type; } } } if (varargs) { char_u *p; // Move the last argument "...name: type" to uf_va_name and // uf_va_type. fp->uf_va_name = ((char_u **)fp->uf_args.ga_data) [fp->uf_args.ga_len - 1]; --fp->uf_args.ga_len; p = ((char_u **)argtypes->ga_data)[len]; if (p == NULL) // TODO: get type from default value fp->uf_va_type = &t_list_any; else { fp->uf_va_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_va_type != NULL && fp->uf_va_type->tt_type != VAR_LIST) { semsg(_(e_variable_arguments_type_must_be_list_str), ((char_u **)argtypes->ga_data)[len]); return FAIL; } } if (fp->uf_va_type == NULL) return FAIL; } return OK; } static int parse_return_type(ufunc_T *fp, char_u *ret_type) { if (ret_type == NULL) fp->uf_ret_type = &t_void; else { char_u *p = ret_type; fp->uf_ret_type = parse_type(&p, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) { fp->uf_ret_type = &t_void; return FAIL; } } return OK; } /* * Register function "fp" as using "current_funccal" as its scope. */ static int register_closure(ufunc_T *fp) { if (fp->uf_scoped == current_funccal) // no change return OK; funccal_unref(fp->uf_scoped, fp, FALSE); fp->uf_scoped = current_funccal; current_funccal->fc_refcount++; if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL) return FAIL; ((ufunc_T **)current_funccal->fc_funcs.ga_data) [current_funccal->fc_funcs.ga_len++] = fp; return OK; } static void set_ufunc_name(ufunc_T *fp, char_u *name) { // Add a type cast to avoid a warning for an overflow, the uf_name[] array // actually extends beyond the struct. STRCPY((void *)fp->uf_name, name); if (name[0] == K_SPECIAL) { fp->uf_name_exp = alloc(STRLEN(name) + 3); if (fp->uf_name_exp != NULL) { STRCPY(fp->uf_name_exp, "<SNR>"); STRCAT(fp->uf_name_exp, fp->uf_name + 3); } } } /* * Get a name for a lambda. Returned in static memory. */ char_u * get_lambda_name(void) { static char_u name[30]; static int lambda_no = 0; sprintf((char*)name, "<lambda>%d", ++lambda_no); return name; } #if defined(FEAT_LUA) || defined(PROTO) /* * Registers a native C callback which can be called from Vim script. * Returns the name of the Vim script function. */ char_u * register_cfunc(cfunc_T cb, cfunc_free_T cb_free, void *state) { char_u *name = get_lambda_name(); ufunc_T *fp; fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) return NULL; fp->uf_def_status = UF_NOT_COMPILED; fp->uf_refcount = 1; fp->uf_varargs = TRUE; fp->uf_flags = FC_CFUNC | FC_LAMBDA; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_cb = cb; fp->uf_cb_free = cb_free; fp->uf_cb_state = state; set_ufunc_name(fp, name); hash_add(&func_hashtab, UF2HIKEY(fp)); return name; } #endif /* * Skip over "->" or "=>" after the arguments of a lambda. * If ": type" is found make "ret_type" point to "type". * If "white_error" is not NULL check for correct use of white space and set * "white_error" to TRUE if there is an error. * Return NULL if no valid arrow found. */ static char_u * skip_arrow( char_u *start, int equal_arrow, char_u **ret_type, int *white_error) { char_u *s = start; char_u *bef = start - 2; // "start" points to > of -> if (equal_arrow) { if (*s == ':') { if (white_error != NULL && !VIM_ISWHITE(s[1])) { *white_error = TRUE; semsg(_(e_white_space_required_after_str_str), ":", s); return NULL; } s = skipwhite(s + 1); *ret_type = s; s = skip_type(s, TRUE); if (s == *ret_type) { emsg(_(e_missing_return_type)); return NULL; } } bef = s; s = skipwhite(s); if (*s != '=') return NULL; ++s; } if (*s != '>') return NULL; if (white_error != NULL && ((!VIM_ISWHITE(*bef) && *bef != '{') || !IS_WHITE_OR_NUL(s[1]))) { *white_error = TRUE; semsg(_(e_white_space_required_before_and_after_str_at_str), equal_arrow ? "=>" : "->", bef); return NULL; } return skipwhite(s + 1); } /* * Check if "*cmd" points to a function command and if so advance "*cmd" and * return TRUE. * Otherwise return FALSE; * Do not consider "function(" to be a command. */ static int is_function_cmd(char_u **cmd) { char_u *p = *cmd; if (checkforcmd(&p, "function", 2)) { if (*p == '(') return FALSE; *cmd = p; return TRUE; } return FALSE; } /* * Called when defining a function: The context may be needed for script * variables declared in a block that is visible now but not when the function * is compiled or called later. */ static void function_using_block_scopes(ufunc_T *fp, cstack_T *cstack) { if (cstack != NULL && cstack->cs_idx >= 0) { int count = cstack->cs_idx + 1; int i; fp->uf_block_ids = ALLOC_MULT(int, count); if (fp->uf_block_ids != NULL) { mch_memmove(fp->uf_block_ids, cstack->cs_block_id, sizeof(int) * count); fp->uf_block_depth = count; } // Set flag in each block to indicate a function was defined. This // is used to keep the variable when leaving the block, see // hide_script_var(). for (i = 0; i <= cstack->cs_idx; ++i) cstack->cs_flags[i] |= CSF_FUNC_DEF; } } /* * Read the body of a function, put every line in "newlines". * This stops at "}", "endfunction" or "enddef". * "newlines" must already have been initialized. * "eap->cmdidx" is CMD_function, CMD_def or CMD_block; */ static int get_function_body( exarg_T *eap, garray_T *newlines, char_u *line_arg_in, garray_T *lines_to_free) { linenr_T sourcing_lnum_top = SOURCING_LNUM; linenr_T sourcing_lnum_off; int saved_wait_return = need_wait_return; char_u *line_arg = line_arg_in; int vim9_function = eap->cmdidx == CMD_def || eap->cmdidx == CMD_block; #define MAX_FUNC_NESTING 50 char nesting_def[MAX_FUNC_NESTING]; char nesting_inline[MAX_FUNC_NESTING]; int nesting = 0; getline_opt_T getline_options; int indent = 2; char_u *skip_until = NULL; int ret = FAIL; int is_heredoc = FALSE; int heredoc_concat_len = 0; garray_T heredoc_ga; char_u *heredoc_trimmed = NULL; ga_init2(&heredoc_ga, 1, 500); // Detect having skipped over comment lines to find the return // type. Add NULL lines to keep the line count correct. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) { sourcing_lnum_off -= SOURCING_LNUM; if (ga_grow(newlines, sourcing_lnum_off) == FAIL) goto theend; while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; } nesting_def[0] = vim9_function; nesting_inline[0] = eap->cmdidx == CMD_block; getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; for (;;) { char_u *theline; char_u *p; char_u *arg; if (KeyTyped) { msg_scroll = TRUE; saved_wait_return = FALSE; } need_wait_return = FALSE; if (line_arg != NULL) { // Use eap->arg, split up in parts by line breaks. theline = line_arg; p = vim_strchr(theline, '\n'); if (p == NULL) line_arg += STRLEN(line_arg); else { *p = NUL; line_arg = p + 1; } } else { theline = get_function_line(eap, lines_to_free, indent, getline_options); } if (KeyTyped) lines_left = Rows - 1; if (theline == NULL) { // Use the start of the function for the line number. SOURCING_LNUM = sourcing_lnum_top; if (skip_until != NULL) semsg(_(e_missing_heredoc_end_marker_str), skip_until); else if (nesting_inline[nesting]) emsg(_(e_missing_end_block)); else if (eap->cmdidx == CMD_def) emsg(_(e_missing_enddef)); else emsg(_(e_missing_endfunction)); goto theend; } // Detect line continuation: SOURCING_LNUM increased more than one. sourcing_lnum_off = get_sourced_lnum(eap->getline, eap->cookie); if (SOURCING_LNUM < sourcing_lnum_off) sourcing_lnum_off -= SOURCING_LNUM; else sourcing_lnum_off = 0; if (skip_until != NULL) { // Don't check for ":endfunc"/":enddef" between // * ":append" and "." // * ":python <<EOF" and "EOF" // * ":let {var-name} =<< [trim] {marker}" and "{marker}" if (heredoc_trimmed == NULL || (is_heredoc && skipwhite(theline) == theline) || STRNCMP(theline, heredoc_trimmed, STRLEN(heredoc_trimmed)) == 0) { if (heredoc_trimmed == NULL) p = theline; else if (is_heredoc) p = skipwhite(theline) == theline ? theline : theline + STRLEN(heredoc_trimmed); else p = theline + STRLEN(heredoc_trimmed); if (STRCMP(p, skip_until) == 0) { VIM_CLEAR(skip_until); VIM_CLEAR(heredoc_trimmed); getline_options = vim9_function ? GETLINE_CONCAT_CONTBAR : GETLINE_CONCAT_CONT; is_heredoc = FALSE; if (heredoc_concat_len > 0) { // Replace the starting line with all the concatenated // lines. ga_concat(&heredoc_ga, theline); vim_free(((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1]); ((char_u **)(newlines->ga_data))[ heredoc_concat_len - 1] = heredoc_ga.ga_data; ga_init(&heredoc_ga); heredoc_concat_len = 0; theline += STRLEN(theline); // skip the "EOF" } } } } else { int c; char_u *end; // skip ':' and blanks for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) ; // Check for "endfunction", "enddef" or "}". // When a ":" follows it must be a dict key; "enddef: value," if (nesting_inline[nesting] ? *p == '}' : (checkforcmd(&p, nesting_def[nesting] ? "enddef" : "endfunction", 4) && *p != ':')) { if (nesting-- == 0) { char_u *nextcmd = NULL; if (*p == '|' || *p == '}') nextcmd = p + 1; else if (line_arg != NULL && *skipwhite(line_arg) != NUL) nextcmd = line_arg; else if (*p != NUL && *p != (vim9_function ? '#' : '"') && (vim9_function || p_verbose > 0)) { SOURCING_LNUM = sourcing_lnum_top + newlines->ga_len + 1; if (eap->cmdidx == CMD_def) semsg(_(e_text_found_after_str_str), "enddef", p); else give_warning2((char_u *) _("W22: Text found after :endfunction: %s"), p, TRUE); } if (nextcmd != NULL && *skipwhite(nextcmd) != NUL) { // Another command follows. If the line came from "eap" // we can simply point into it, otherwise we need to // change "eap->cmdlinep" to point to the last fetched // line. eap->nextcmd = nextcmd; if (lines_to_free->ga_len > 0 && *eap->cmdlinep != ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]) { // *cmdlinep will be freed later, thus remove the // line from lines_to_free. vim_free(*eap->cmdlinep); *eap->cmdlinep = ((char_u **)lines_to_free->ga_data) [lines_to_free->ga_len - 1]; --lines_to_free->ga_len; } } break; } } // Check for mismatched "endfunc" or "enddef". // We don't check for "def" inside "func" thus we also can't check // for "enddef". // We continue to find the end of the function, although we might // not find it. else if (nesting_def[nesting]) { if (checkforcmd(&p, "endfunction", 4) && *p != ':') emsg(_(e_mismatched_endfunction)); } else if (eap->cmdidx == CMD_def && checkforcmd(&p, "enddef", 4)) emsg(_(e_mismatched_enddef)); // Increase indent inside "if", "while", "for" and "try", decrease // at "end". if (indent > 2 && (*p == '}' || STRNCMP(p, "end", 3) == 0)) indent -= 2; else if (STRNCMP(p, "if", 2) == 0 || STRNCMP(p, "wh", 2) == 0 || STRNCMP(p, "for", 3) == 0 || STRNCMP(p, "try", 3) == 0) indent += 2; // Check for defining a function inside this function. // Only recognize "def" inside "def", not inside "function", // For backwards compatibility, see Test_function_python(). c = *p; if (is_function_cmd(&p) || (eap->cmdidx == CMD_def && checkforcmd(&p, "def", 3))) { if (*p == '!') p = skipwhite(p + 1); p += eval_fname_script(p); vim_free(trans_function_name(&p, NULL, TRUE, 0, NULL, NULL, NULL)); if (*skipwhite(p) == '(') { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = (c == 'd'); nesting_inline[nesting] = FALSE; indent += 2; } } } if (nesting_def[nesting] ? *p != '#' : *p != '"') { // Not a comment line: check for nested inline function. end = p + STRLEN(p) - 1; while (end > p && VIM_ISWHITE(*end)) --end; if (end > p + 1 && *end == '{' && VIM_ISWHITE(end[-1])) { int is_block; // check for trailing "=> {": start of an inline function --end; while (end > p && VIM_ISWHITE(*end)) --end; is_block = end > p + 2 && end[-1] == '=' && end[0] == '>'; if (!is_block) { char_u *s = p; // check for line starting with "au" for :autocmd or // "com" for :command, these can use a {} block is_block = checkforcmd_noparen(&s, "autocmd", 2) || checkforcmd_noparen(&s, "command", 3); } if (is_block) { if (nesting == MAX_FUNC_NESTING - 1) emsg(_(e_function_nesting_too_deep)); else { ++nesting; nesting_def[nesting] = TRUE; nesting_inline[nesting] = TRUE; indent += 2; } } } } // Check for ":append", ":change", ":insert". Not for :def. p = skip_range(p, FALSE, NULL); if (!vim9_function && ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) || (p[0] == 'c' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' && (STRNCMP(&p[3], "nge", 3) != 0 || !ASCII_ISALPHA(p[6]))))))) || (p[0] == 'i' && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' && (!ASCII_ISALPHA(p[2]) || (p[2] == 's' && (!ASCII_ISALPHA(p[3]) || p[3] == 'e')))))))) skip_until = vim_strsave((char_u *)"."); // Check for ":python <<EOF", ":tcl <<EOF", etc. arg = skipwhite(skiptowhite(p)); if (arg[0] == '<' && arg[1] =='<' && ((p[0] == 'p' && p[1] == 'y' && (!ASCII_ISALNUM(p[2]) || p[2] == 't' || ((p[2] == '3' || p[2] == 'x') && !ASCII_ISALPHA(p[3])))) || (p[0] == 'p' && p[1] == 'e' && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) || (p[0] == 't' && p[1] == 'c' && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' && !ASCII_ISALPHA(p[3])) || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) || (p[0] == 'm' && p[1] == 'z' && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) )) { // ":python <<" continues until a dot, like ":append" p = skipwhite(arg + 2); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } if (*p == NUL) skip_until = vim_strsave((char_u *)"."); else skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; if (eap->cmdidx == CMD_def) heredoc_concat_len = newlines->ga_len + 1; } // Check for ":cmd v =<< [trim] EOF" // and ":cmd [a, b] =<< [trim] EOF" // and "lines =<< [trim] EOF" for Vim9 // Where "cmd" can be "let", "var", "final" or "const". arg = skipwhite(skiptowhite(p)); if (*arg == '[') arg = vim_strchr(arg, ']'); if (arg != NULL) { int found = (eap->cmdidx == CMD_def && arg[0] == '=' && arg[1] == '<' && arg[2] =='<'); if (!found) // skip over the argument after "cmd" arg = skipwhite(skiptowhite(arg)); if (found || (arg[0] == '=' && arg[1] == '<' && arg[2] =='<' && (checkforcmd(&p, "let", 2) || checkforcmd(&p, "var", 3) || checkforcmd(&p, "final", 5) || checkforcmd(&p, "const", 5)))) { p = skipwhite(arg + 3); if (STRNCMP(p, "trim", 4) == 0) { // Ignore leading white space. p = skipwhite(p + 4); heredoc_trimmed = vim_strnsave(theline, skipwhite(theline) - theline); } skip_until = vim_strnsave(p, skiptowhite(p) - p); getline_options = GETLINE_NONE; is_heredoc = TRUE; } } } // Add the line to the function. if (ga_grow(newlines, 1 + sourcing_lnum_off) == FAIL) goto theend; if (heredoc_concat_len > 0) { // For a :def function "python << EOF" concatenates all the lines, // to be used for the instruction later. ga_concat(&heredoc_ga, theline); ga_concat(&heredoc_ga, (char_u *)"\n"); p = vim_strsave((char_u *)""); } else { // Copy the line to newly allocated memory. get_one_sourceline() // allocates 250 bytes per line, this saves 80% on average. The // cost is an extra alloc/free. p = vim_strsave(theline); } if (p == NULL) goto theend; ((char_u **)(newlines->ga_data))[newlines->ga_len++] = p; // Add NULL lines for continuation lines, so that the line count is // equal to the index in the growarray. while (sourcing_lnum_off-- > 0) ((char_u **)(newlines->ga_data))[newlines->ga_len++] = NULL; // Check for end of eap->arg. if (line_arg != NULL && *line_arg == NUL) line_arg = NULL; } // Return OK when no error was detected. if (!did_emsg) ret = OK; theend: vim_free(skip_until); vim_free(heredoc_trimmed); vim_free(heredoc_ga.ga_data); need_wait_return |= saved_wait_return; return ret; } /* * Handle the body of a lambda. *arg points to the "{", process statements * until the matching "}". * When not evaluating "newargs" is NULL. * When successful "rettv" is set to a funcref. */ static int lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; } /* * Parse a lambda expression and get a Funcref from "*arg" into "rettv". * "arg" points to the { in "{arg -> expr}" or the ( in "(arg) => expr" * When "types_optional" is TRUE optionally take argument types. * Return OK or FAIL. Returns NOTDONE for dict or {expr}. */ int get_lambda_tv( char_u **arg, typval_T *rettv, int types_optional, evalarg_T *evalarg) { int evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE); garray_T newargs; garray_T newlines; garray_T *pnewargs; garray_T argtypes; garray_T default_args; ufunc_T *fp = NULL; partial_T *pt = NULL; int varargs; char_u *ret_type = NULL; int ret; char_u *s; char_u *start, *end; int *old_eval_lavars = eval_lavars_used; int eval_lavars = FALSE; char_u *tofree1 = NULL; char_u *tofree2 = NULL; int equal_arrow = **arg == '('; int white_error = FALSE; int called_emsg_start = called_emsg; if (equal_arrow && !in_vim9script()) return NOTDONE; ga_init(&newargs); ga_init(&newlines); // First, check if this is really a lambda expression. "->" or "=>" must // be found after the arguments. s = *arg + 1; ret = get_function_args(&s, equal_arrow ? ')' : '-', NULL, types_optional ? &argtypes : NULL, types_optional, evalarg, NULL, &default_args, TRUE, NULL, NULL); if (ret == FAIL || skip_arrow(s, equal_arrow, &ret_type, NULL) == NULL) { if (types_optional) ga_clear_strings(&argtypes); return called_emsg == called_emsg_start ? NOTDONE : FAIL; } // Parse the arguments for real. if (evaluate) pnewargs = &newargs; else pnewargs = NULL; *arg += 1; ret = get_function_args(arg, equal_arrow ? ')' : '-', pnewargs, types_optional ? &argtypes : NULL, types_optional, evalarg, &varargs, &default_args, FALSE, NULL, NULL); if (ret == FAIL || (s = skip_arrow(*arg, equal_arrow, &ret_type, equal_arrow || in_vim9script() ? &white_error : NULL)) == NULL) { if (types_optional) ga_clear_strings(&argtypes); ga_clear_strings(&newargs); return white_error ? FAIL : NOTDONE; } *arg = s; // Skipping over linebreaks may make "ret_type" invalid, make a copy. if (ret_type != NULL) { ret_type = vim_strsave(ret_type); tofree2 = ret_type; } // Set up a flag for checking local variables and arguments. if (evaluate) eval_lavars_used = &eval_lavars; *arg = skipwhite_and_linebreak(*arg, evalarg); // Recognize "{" as the start of a function body. if (equal_arrow && **arg == '{') { if (evalarg == NULL) // cannot happen? goto theend; if (lambda_function_body(arg, rettv, evalarg, pnewargs, types_optional ? &argtypes : NULL, varargs, &default_args, ret_type) == FAIL) goto errret; goto theend; } if (default_args.ga_len > 0) { emsg(_(e_cannot_use_default_values_in_lambda)); goto errret; } // Get the start and the end of the expression. start = *arg; ret = skip_expr_concatenate(arg, &start, &end, evalarg); if (ret == FAIL) goto errret; if (evalarg != NULL) { // avoid that the expression gets freed when another line break follows tofree1 = evalarg->eval_tofree; evalarg->eval_tofree = NULL; } if (!equal_arrow) { *arg = skipwhite_and_linebreak(*arg, evalarg); if (**arg != '}') { semsg(_(e_expected_right_curly_str), *arg); goto errret; } ++*arg; } if (evaluate) { int len; int flags = FC_LAMBDA; char_u *p; char_u *line_end; char_u *name = get_lambda_name(); fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto errret; fp->uf_def_status = UF_NOT_COMPILED; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto errret; ga_init2(&newlines, (int)sizeof(char_u *), 1); if (ga_grow(&newlines, 1) == FAIL) goto errret; // If there are line breaks, we need to split up the string. line_end = vim_strchr(start, '\n'); if (line_end == NULL || line_end > end) line_end = end; // Add "return " before the expression (or the first line). len = 7 + (int)(line_end - start) + 1; p = alloc(len); if (p == NULL) goto errret; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; STRCPY(p, "return "); vim_strncpy(p + 7, start, line_end - start); if (line_end != end) { // Add more lines, split by line breaks. Thus is used when a // lambda with { cmds } is encountered. while (*line_end == '\n') { if (ga_grow(&newlines, 1) == FAIL) goto errret; start = line_end + 1; line_end = vim_strchr(start, '\n'); if (line_end == NULL) line_end = end; ((char_u **)(newlines.ga_data))[newlines.ga_len++] = vim_strnsave(start, line_end - start); } } if (strstr((char *)p + 7, "a:") == NULL) // No a: variables are used for sure. flags |= FC_NOARGS; fp->uf_refcount = 1; set_ufunc_name(fp, name); fp->uf_args = newargs; ga_init(&fp->uf_def_args); if (types_optional) { if (parse_argument_types(fp, &argtypes, in_vim9script() && varargs) == FAIL) goto errret; if (ret_type != NULL) { fp->uf_ret_type = parse_type(&ret_type, &fp->uf_type_list, TRUE); if (fp->uf_ret_type == NULL) goto errret; } else fp->uf_ret_type = &t_unknown; } fp->uf_lines = newlines; if (current_funccal != NULL && eval_lavars) { flags |= FC_CLOSURE; if (register_closure(fp) == FAIL) goto errret; } #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif if (sandbox) flags |= FC_SANDBOX; // In legacy script a lambda can be called with more args than // uf_args.ga_len. In Vim9 script "...name" has to be used. fp->uf_varargs = !in_vim9script() || varargs; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len + 1; function_using_block_scopes(fp, evalarg->eval_cstack); pt->pt_func = fp; pt->pt_refcount = 1; rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; hash_add(&func_hashtab, UF2HIKEY(fp)); } theend: eval_lavars_used = old_eval_lavars; if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); if (types_optional) ga_clear_strings(&argtypes); return OK; errret: ga_clear_strings(&newargs); ga_clear_strings(&newlines); ga_clear_strings(&default_args); if (types_optional) { ga_clear_strings(&argtypes); if (fp != NULL) vim_free(fp->uf_arg_types); } vim_free(fp); vim_free(pt); if (evalarg != NULL && evalarg->eval_tofree == NULL) evalarg->eval_tofree = tofree1; else vim_free(tofree1); vim_free(tofree2); eval_lavars_used = old_eval_lavars; return FAIL; } /* * Check if "name" is a variable of type VAR_FUNC. If so, return the function * name it contains, otherwise return "name". * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set * "partialp". * If "type" is not NULL and a Vim9 script-local variable is found look up the * type of the variable. * If "found_var" is not NULL and a variable was found set it to TRUE. */ char_u * deref_func_name( char_u *name, int *lenp, partial_T **partialp, type_T **type, int no_autoload, int *found_var) { dictitem_T *v; typval_T *tv = NULL; int cc; char_u *s = NULL; hashtab_T *ht; int did_type = FALSE; if (partialp != NULL) *partialp = NULL; cc = name[*lenp]; name[*lenp] = NUL; v = find_var_also_in_script(name, &ht, no_autoload); name[*lenp] = cc; if (v != NULL) { tv = &v->di_tv; } else if (in_vim9script() || STRNCMP(name, "s:", 2) == 0) { imported_T *import; char_u *p = name; int len = *lenp; if (STRNCMP(name, "s:", 2) == 0) { p = name + 2; len -= 2; } import = find_imported(p, len, NULL); // imported function from another script if (import != NULL) { name[len] = NUL; semsg(_(e_cannot_use_str_itself_it_is_imported), name); name[len] = cc; *lenp = 0; return (char_u *)""; // just in case } } if (tv != NULL) { if (found_var != NULL) *found_var = TRUE; if (tv->v_type == VAR_FUNC) { if (tv->vval.v_string == NULL) { *lenp = 0; return (char_u *)""; // just in case } s = tv->vval.v_string; *lenp = (int)STRLEN(s); } if (tv->v_type == VAR_PARTIAL) { partial_T *pt = tv->vval.v_partial; if (pt == NULL) { *lenp = 0; return (char_u *)""; // just in case } if (partialp != NULL) *partialp = pt; s = partial_name(pt); *lenp = (int)STRLEN(s); } if (s != NULL) { if (!did_type && type != NULL && ht == get_script_local_ht()) { svar_T *sv = find_typval_in_script(tv, 0); if (sv != NULL) *type = sv->sv_type; } return s; } } return name; } /* * Give an error message with a function name. Handle <SNR> things. * "ermsg" is to be passed without translation, use N_() instead of _(). */ void emsg_funcname(char *ermsg, char_u *name) { char_u *p; if (*name == K_SPECIAL) p = concat_str((char_u *)"<SNR>", name + 3); else p = name; semsg(_(ermsg), p); if (p != name) vim_free(p); } /* * Allocate a variable for the result of a function. * Return OK or FAIL. */ int get_func_tv( char_u *name, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, char_u **arg, // argument, pointing to the '(' evalarg_T *evalarg, // for line continuation funcexe_T *funcexe) // various values { char_u *argp; int ret = OK; typval_T argvars[MAX_FUNC_ARGS + 1]; // vars for arguments int argcount = 0; // number of arguments found int vim9script = in_vim9script(); /* * Get the arguments. */ argp = *arg; while (argcount < MAX_FUNC_ARGS - (funcexe->fe_partial == NULL ? 0 : funcexe->fe_partial->pt_argc)) { // skip the '(' or ',' and possibly line breaks argp = skipwhite_and_linebreak(argp + 1, evalarg); if (*argp == ')' || *argp == ',' || *argp == NUL) break; if (eval1(&argp, &argvars[argcount], evalarg) == FAIL) { ret = FAIL; break; } ++argcount; // The comma should come right after the argument, but this wasn't // checked previously, thus only enforce it in Vim9 script. if (vim9script) { if (*argp != ',' && *skipwhite(argp) == ',') { semsg(_(e_no_white_space_allowed_before_str_str), ",", argp); ret = FAIL; break; } } else argp = skipwhite(argp); if (*argp != ',') break; if (vim9script && !IS_WHITE_OR_NUL(argp[1])) { semsg(_(e_white_space_required_after_str_str), ",", argp); ret = FAIL; break; } } argp = skipwhite_and_linebreak(argp, evalarg); if (*argp == ')') ++argp; else ret = FAIL; if (ret == OK) { int i = 0; int did_emsg_before = did_emsg; if (get_vim_var_nr(VV_TESTING)) { // Prepare for calling test_garbagecollect_now(), need to know // what variables are used on the call stack. if (funcargs.ga_itemsize == 0) ga_init2(&funcargs, (int)sizeof(typval_T *), 50); for (i = 0; i < argcount; ++i) if (ga_grow(&funcargs, 1) == OK) ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; } ret = call_func(name, len, rettv, argcount, argvars, funcexe); if (in_vim9script() && did_emsg > did_emsg_before) { // An error in a builtin function does not return FAIL, but we do // want to abort further processing if an error was given. ret = FAIL; clear_tv(rettv); } funcargs.ga_len -= i; } else if (!aborting()) { if (argcount == MAX_FUNC_ARGS) emsg_funcname(e_too_many_arguments_for_function_str_2, name); else emsg_funcname(e_invalid_arguments_for_function_str, name); } while (--argcount >= 0) clear_tv(&argvars[argcount]); if (in_vim9script()) *arg = argp; else *arg = skipwhite(argp); return ret; } /* * Return TRUE if "p" starts with "<SID>" or "s:". * Only works if eval_fname_script() returned non-zero for "p"! */ static int eval_fname_sid(char_u *p) { return (*p == 's' || TOUPPER_ASC(p[2]) == 'I'); } /* * In a script change <SID>name() and s:name() to K_SNR 123_name(). * Change <SNR>123_name() to K_SNR 123_name(). * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory * (slow). */ char_u * fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error) { int llen; char_u *fname; int i; llen = eval_fname_script(name); if (llen > 0) { fname_buf[0] = K_SPECIAL; fname_buf[1] = KS_EXTRA; fname_buf[2] = (int)KE_SNR; i = 3; if (eval_fname_sid(name)) // "<SID>" or "s:" { if (current_sctx.sc_sid <= 0) *error = FCERR_SCRIPT; else { sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid); i = (int)STRLEN(fname_buf); } } if (i + STRLEN(name + llen) < FLEN_FIXED) { STRCPY(fname_buf + i, name + llen); fname = fname_buf; } else { fname = alloc(i + STRLEN(name + llen) + 1); if (fname == NULL) *error = FCERR_OTHER; else { *tofree = fname; mch_memmove(fname, fname_buf, (size_t)i); STRCPY(fname + i, name + llen); } } } else fname = name; return fname; } /* * Find a function "name" in script "sid". */ static ufunc_T * find_func_with_sid(char_u *name, int sid) { hashitem_T *hi; char_u buffer[200]; buffer[0] = K_SPECIAL; buffer[1] = KS_EXTRA; buffer[2] = (int)KE_SNR; vim_snprintf((char *)buffer + 3, sizeof(buffer) - 3, "%ld_%s", (long)sid, name); hi = hash_find(&func_hashtab, buffer); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * When "is_global" is true don't find script-local or imported functions. * Return NULL for unknown function. */ ufunc_T * find_func_even_dead(char_u *name, int is_global, cctx_T *cctx UNUSED) { hashitem_T *hi; ufunc_T *func; if (!is_global) { int find_script_local = in_vim9script() && eval_isnamec1(*name) && (name[1] != ':' || *name == 's'); if (find_script_local) { // Find script-local function before global one. func = find_func_with_sid(name[0] == 's' && name[1] == ':' ? name + 2 : name, current_sctx.sc_sid); if (func != NULL) return func; } } hi = hash_find(&func_hashtab, STRNCMP(name, "g:", 2) == 0 ? name + 2 : name); if (!HASHITEM_EMPTY(hi)) return HI2UF(hi); return NULL; } /* * Find a function by name, return pointer to it in ufuncs. * "cctx" is passed in a :def function to find imported functions. * Return NULL for unknown or dead function. */ ufunc_T * find_func(char_u *name, int is_global, cctx_T *cctx) { ufunc_T *fp = find_func_even_dead(name, is_global, cctx); if (fp != NULL && (fp->uf_flags & FC_DEAD) == 0) return fp; return NULL; } /* * Return TRUE if "ufunc" is a global function. */ int func_is_global(ufunc_T *ufunc) { return ufunc->uf_name[0] != K_SPECIAL; } /* * Copy the function name of "fp" to buffer "buf". * "buf" must be able to hold the function name plus three bytes. * Takes care of script-local function names. */ static void cat_func_name(char_u *buf, ufunc_T *fp) { if (!func_is_global(fp)) { STRCPY(buf, "<SNR>"); STRCAT(buf, fp->uf_name + 3); } else STRCPY(buf, fp->uf_name); } /* * Add a number variable "name" to dict "dp" with value "nr". */ static void add_nr_var( dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) { STRCPY(v->di_key, name); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&dp->dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_NUMBER; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_number = nr; } /* * Free "fc". */ static void free_funccal(funccall_T *fc) { int i; for (i = 0; i < fc->fc_funcs.ga_len; ++i) { ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; // When garbage collecting a funccall_T may be freed before the // function that references it, clear its uf_scoped field. // The function may have been redefined and point to another // funccall_T, don't clear it then. if (fp != NULL && fp->uf_scoped == fc) fp->uf_scoped = NULL; } ga_clear(&fc->fc_funcs); func_ptr_unref(fc->func); vim_free(fc); } /* * Free "fc" and what it contains. * Can be called only when "fc" is kept beyond the period of it called, * i.e. after cleanup_function_call(fc). */ static void free_funccal_contents(funccall_T *fc) { listitem_T *li; // Free all l: variables. vars_clear(&fc->l_vars.dv_hashtab); // Free all a: variables. vars_clear(&fc->l_avars.dv_hashtab); // Free the a:000 variables. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) clear_tv(&li->li_tv); free_funccal(fc); } /* * Handle the last part of returning from a function: free the local hashtable. * Unless it is still in use by a closure. */ static void cleanup_function_call(funccall_T *fc) { int may_free_fc = fc->fc_refcount <= 0; int free_fc = TRUE; current_funccal = fc->caller; // Free all l: variables if not referred. if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT) vars_clear(&fc->l_vars.dv_hashtab); else free_fc = FALSE; // If the a:000 list and the l: and a: dicts are not referenced and // there is no closure using it, we can free the funccall_T and what's // in it. if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT) vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE); else { int todo; hashitem_T *hi; dictitem_T *di; free_fc = FALSE; // Make a copy of the a: variables, since we didn't do that above. todo = (int)fc->l_avars.dv_hashtab.ht_used; for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; di = HI2DI(hi); copy_tv(&di->di_tv, &di->di_tv); } } } if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT) fc->l_varlist.lv_first = NULL; else { listitem_T *li; free_fc = FALSE; // Make a copy of the a:000 items, since we didn't do that above. FOR_ALL_LIST_ITEMS(&fc->l_varlist, li) copy_tv(&li->li_tv, &li->li_tv); } if (free_fc) free_funccal(fc); else { static int made_copy = 0; // "fc" is still in use. This can happen when returning "a:000", // assigning "l:" to a global variable or defining a closure. // Link "fc" in the list for garbage collection later. fc->caller = previous_funccal; previous_funccal = fc; if (want_garbage_collect) // If garbage collector is ready, clear count. made_copy = 0; else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) { // We have made a lot of copies, worth 4 Mbyte. This can happen // when repetitively calling a function that creates a reference to // itself somehow. Call the garbage collector soon to avoid using // too much memory. made_copy = 0; want_garbage_collect = TRUE; } } } /* * Return TRUE if "name" is a numbered function, ignoring a "g:" prefix. */ static int numbered_function(char_u *name) { return isdigit(*name) || (name[0] == 'g' && name[1] == ':' && isdigit(name[2])); } /* * There are two kinds of function names: * 1. ordinary names, function defined with :function or :def * 2. numbered functions and lambdas * For the first we only count the name stored in func_hashtab as a reference, * using function() does not count as a reference, because the function is * looked up by name. */ int func_name_refcount(char_u *name) { return numbered_function(name) || *name == '<'; } /* * Unreference "fc": decrement the reference count and free it when it * becomes zero. "fp" is detached from "fc". * When "force" is TRUE we are exiting. */ static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force) { funccall_T **pfc; int i; if (fc == NULL) return; if (--fc->fc_refcount <= 0 && (force || ( fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT))) for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { if (fc == *pfc) { *pfc = fc->caller; free_funccal_contents(fc); return; } } for (i = 0; i < fc->fc_funcs.ga_len; ++i) if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; } /* * Remove the function from the function hashtable. If the function was * deleted while it still has references this was already done. * Return TRUE if the entry was deleted, FALSE if it wasn't found. */ static int func_remove(ufunc_T *fp) { hashitem_T *hi; // Return if it was already virtually deleted. if (fp->uf_flags & FC_DEAD) return FALSE; hi = hash_find(&func_hashtab, UF2HIKEY(fp)); if (!HASHITEM_EMPTY(hi)) { // When there is a def-function index do not actually remove the // function, so we can find the index when defining the function again. // Do remove it when it's a copy. if (fp->uf_def_status == UF_COMPILED && (fp->uf_flags & FC_COPY) == 0) { fp->uf_flags |= FC_DEAD; return FALSE; } hash_remove(&func_hashtab, hi); fp->uf_flags |= FC_DELETED; return TRUE; } return FALSE; } static void func_clear_items(ufunc_T *fp) { ga_clear_strings(&(fp->uf_args)); ga_clear_strings(&(fp->uf_def_args)); ga_clear_strings(&(fp->uf_lines)); VIM_CLEAR(fp->uf_arg_types); VIM_CLEAR(fp->uf_block_ids); VIM_CLEAR(fp->uf_va_name); clear_type_list(&fp->uf_type_list); // Increment the refcount of this function to avoid it being freed // recursively when the partial is freed. fp->uf_refcount += 3; partial_unref(fp->uf_partial); fp->uf_partial = NULL; fp->uf_refcount -= 3; #ifdef FEAT_LUA if (fp->uf_cb_free != NULL) { fp->uf_cb_free(fp->uf_cb_state); fp->uf_cb_free = NULL; } fp->uf_cb_state = NULL; fp->uf_cb = NULL; #endif #ifdef FEAT_PROFILE VIM_CLEAR(fp->uf_tml_count); VIM_CLEAR(fp->uf_tml_total); VIM_CLEAR(fp->uf_tml_self); #endif } /* * Free all things that a function contains. Does not free the function * itself, use func_free() for that. * When "force" is TRUE we are exiting. */ static void func_clear(ufunc_T *fp, int force) { if (fp->uf_cleared) return; fp->uf_cleared = TRUE; // clear this function func_clear_items(fp); funccal_unref(fp->uf_scoped, fp, force); unlink_def_function(fp); } /* * Free a function and remove it from the list of functions. Does not free * what a function contains, call func_clear() first. * When "force" is TRUE we are exiting. * Returns OK when the function was actually freed. */ static int func_free(ufunc_T *fp, int force) { // Only remove it when not done already, otherwise we would remove a newer // version of the function with the same name. if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) func_remove(fp); if ((fp->uf_flags & FC_DEAD) == 0 || force) { if (fp->uf_dfunc_idx > 0) unlink_def_function(fp); VIM_CLEAR(fp->uf_name_exp); vim_free(fp); return OK; } return FAIL; } /* * Free all things that a function contains and free the function itself. * When "force" is TRUE we are exiting. */ void func_clear_free(ufunc_T *fp, int force) { func_clear(fp, force); if (force || fp->uf_dfunc_idx == 0 || func_name_refcount(fp->uf_name) || (fp->uf_flags & FC_COPY)) func_free(fp, force); else fp->uf_flags |= FC_DEAD; } /* * Copy already defined function "lambda" to a new function with name "global". * This is for when a compiled function defines a global function. */ int copy_func(char_u *lambda, char_u *global, ectx_T *ectx) { ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL); ufunc_T *fp = NULL; if (ufunc == NULL) { semsg(_(e_lambda_function_not_found_str), lambda); return FAIL; } fp = find_func(global, TRUE, NULL); if (fp != NULL) { // TODO: handle ! to overwrite semsg(_(e_function_str_already_exists_add_bang_to_replace), global); return FAIL; } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(global) + 1); if (fp == NULL) return FAIL; fp->uf_varargs = ufunc->uf_varargs; fp->uf_flags = (ufunc->uf_flags & ~FC_VIM9) | FC_COPY; fp->uf_def_status = ufunc->uf_def_status; fp->uf_dfunc_idx = ufunc->uf_dfunc_idx; if (ga_copy_strings(&ufunc->uf_args, &fp->uf_args) == FAIL || ga_copy_strings(&ufunc->uf_def_args, &fp->uf_def_args) == FAIL || ga_copy_strings(&ufunc->uf_lines, &fp->uf_lines) == FAIL) goto failed; fp->uf_name_exp = ufunc->uf_name_exp == NULL ? NULL : vim_strsave(ufunc->uf_name_exp); if (ufunc->uf_arg_types != NULL) { fp->uf_arg_types = ALLOC_MULT(type_T *, fp->uf_args.ga_len); if (fp->uf_arg_types == NULL) goto failed; mch_memmove(fp->uf_arg_types, ufunc->uf_arg_types, sizeof(type_T *) * fp->uf_args.ga_len); } if (ufunc->uf_va_name != NULL) { fp->uf_va_name = vim_strsave(ufunc->uf_va_name); if (fp->uf_va_name == NULL) goto failed; } fp->uf_ret_type = ufunc->uf_ret_type; fp->uf_refcount = 1; STRCPY(fp->uf_name, global); hash_add(&func_hashtab, UF2HIKEY(fp)); // the referenced dfunc_T is now used one more time link_def_function(fp); // Create a partial to store the context of the function where it was // instantiated. Only needs to be done once. Do this on the original // function, "dfunc->df_ufunc" will point to it. if ((ufunc->uf_flags & FC_CLOSURE) && ufunc->uf_partial == NULL) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto failed; if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL) { vim_free(pt); goto failed; } ufunc->uf_partial = pt; --pt->pt_refcount; // not actually referenced here } return OK; failed: func_clear_free(fp, TRUE); return FAIL; } static int funcdepth = 0; /* * Increment the function call depth count. * Return FAIL when going over 'maxfuncdepth'. * Otherwise return OK, must call funcdepth_decrement() later! */ int funcdepth_increment(void) { if (funcdepth >= p_mfd) { emsg(_(e_function_call_depth_is_higher_than_macfuncdepth)); return FAIL; } ++funcdepth; return OK; } void funcdepth_decrement(void) { --funcdepth; } /* * Get the current function call depth. */ int funcdepth_get(void) { return funcdepth; } /* * Restore the function call depth. This is for cases where there is no * guarantee funcdepth_decrement() can be called exactly the same number of * times as funcdepth_increment(). */ void funcdepth_restore(int depth) { funcdepth = depth; } /* * Call a user function. */ static void call_user_func( ufunc_T *fp, // pointer to function int argcount, // nr of args typval_T *argvars, // arguments typval_T *rettv, // return value funcexe_T *funcexe, // context dict_T *selfdict) // Dictionary for "self" { sctx_T save_current_sctx; int using_sandbox = FALSE; funccall_T *fc; int save_did_emsg; int default_arg_err = FALSE; dictitem_T *v; int fixvar_idx = 0; // index in fixvar[] int i; int ai; int islambda = FALSE; char_u numbuf[NUMBUFLEN]; char_u *name; typval_T *tv_to_free[MAX_FUNC_ARGS]; int tv_to_free_len = 0; #ifdef FEAT_PROFILE profinfo_T profile_info; #endif ESTACK_CHECK_DECLARATION #ifdef FEAT_PROFILE CLEAR_FIELD(profile_info); #endif // If depth of calling is getting too high, don't execute the function. if (funcdepth_increment() == FAIL) { rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; return; } line_breakcheck(); // check for CTRL-C hit fc = ALLOC_CLEAR_ONE(funccall_T); if (fc == NULL) return; fc->caller = current_funccal; current_funccal = fc; fc->func = fp; fc->rettv = rettv; fc->level = ex_nesting_level; // Check if this function has a breakpoint. fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); fc->dbg_tick = debug_tick; // Set up fields for closure. ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1); func_ptr_ref(fp); if (fp->uf_def_status != UF_NOT_COMPILED) { #ifdef FEAT_PROFILE ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; #endif // Execute the function, possibly compiling it first. #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, caller); #endif call_def_function(fp, argcount, argvars, funcexe->fe_partial, rettv); funcdepth_decrement(); #ifdef FEAT_PROFILE if (do_profiling == PROF_YES && (fp->uf_profiling || (caller != NULL && caller->uf_profiling))) profile_may_end_func(&profile_info, fp, caller); #endif current_funccal = fc->caller; free_funccal(fc); return; } islambda = fp->uf_flags & FC_LAMBDA; /* * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free * each argument variable and saves a lot of time. */ /* * Init l: variables. */ init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); if (selfdict != NULL) { // Set l:self to "selfdict". Use "name" to avoid a warning from // some compiler that checks the destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "self"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_DICT; v->di_tv.v_lock = 0; v->di_tv.vval.v_dict = selfdict; ++selfdict->dv_refcount; } /* * Init a: variables, unless none found (in lambda). * Set a:0 to "argcount" less number of named arguments, if >= 0. * Set a:000 to a list with room for the "..." arguments. */ init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); if ((fp->uf_flags & FC_NOARGS) == 0) add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0", (varnumber_T)(argcount >= fp->uf_args.ga_len ? argcount - fp->uf_args.ga_len : 0)); fc->l_avars.dv_lock = VAR_FIXED; if ((fp->uf_flags & FC_NOARGS) == 0) { // Use "name" to avoid a warning from some compiler that checks the // destination size. v = &fc->fixvar[fixvar_idx++].var; name = v->di_key; STRCPY(name, "000"); v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); v->di_tv.v_type = VAR_LIST; v->di_tv.v_lock = VAR_FIXED; v->di_tv.vval.v_list = &fc->l_varlist; } CLEAR_FIELD(fc->l_varlist); fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT; fc->l_varlist.lv_lock = VAR_FIXED; /* * Set a:firstline to "firstline" and a:lastline to "lastline". * Set a:name to named arguments. * Set a:N to the "..." arguments. * Skipped when no a: variables used (in lambda). */ if ((fp->uf_flags & FC_NOARGS) == 0) { add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline", (varnumber_T)funcexe->fe_firstline); add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline", (varnumber_T)funcexe->fe_lastline); } for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i) { int addlocal = FALSE; typval_T def_rettv; int isdefault = FALSE; ai = i - fp->uf_args.ga_len; if (ai < 0) { // named argument a:name name = FUNCARG(fp, i); if (islambda) addlocal = TRUE; // evaluate named argument default expression isdefault = ai + fp->uf_def_args.ga_len >= 0 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL && argvars[i].vval.v_number == VVAL_NONE)); if (isdefault) { char_u *default_expr = NULL; def_rettv.v_type = VAR_NUMBER; def_rettv.vval.v_number = -1; default_expr = ((char_u **)(fp->uf_def_args.ga_data)) [ai + fp->uf_def_args.ga_len]; if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) { default_arg_err = 1; break; } } } else { if ((fp->uf_flags & FC_NOARGS) != 0) // Bail out if no a: arguments used (in lambda). break; // "..." argument a:1, a:2, etc. sprintf((char *)numbuf, "%d", ai + 1); name = numbuf; } if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { v = &fc->fixvar[fixvar_idx++].var; v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; STRCPY(v->di_key, name); } else { v = dictitem_alloc(name); if (v == NULL) break; v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX; } // Note: the values are copied directly to avoid alloc/free. // "argvars" must have VAR_FIXED for v_lock. v->di_tv = isdefault ? def_rettv : argvars[i]; v->di_tv.v_lock = VAR_FIXED; if (isdefault) // Need to free this later, no matter where it's stored. tv_to_free[tv_to_free_len++] = &v->di_tv; if (addlocal) { // Named arguments should be accessed without the "a:" prefix in // lambda expressions. Add to the l: dict. copy_tv(&v->di_tv, &v->di_tv); hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v)); } else hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v)); if (ai >= 0 && ai < MAX_FUNC_ARGS) { listitem_T *li = &fc->l_listitems[ai]; li->li_tv = argvars[i]; li->li_tv.v_lock = VAR_FIXED; list_append(&fc->l_varlist, li); } } // Don't redraw while executing the function. ++RedrawingDisabled; if (fp->uf_flags & FC_SANDBOX) { using_sandbox = TRUE; ++sandbox; } estack_push_ufunc(fp, 1); ESTACK_CHECK_SETUP if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); smsg(_("calling %s"), SOURCING_NAME); if (p_verbose >= 14) { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; msg_puts("("); for (i = 0; i < argcount; ++i) { if (i > 0) msg_puts(", "); if (argvars[i].v_type == VAR_NUMBER) msg_outnum((long)argvars[i].vval.v_number); else { // Do not want errors such as E724 here. ++emsg_off; s = tv2string(&argvars[i], &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } msg_puts((char *)s); vim_free(tofree); } } } msg_puts(")"); } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) profile_may_start_func(&profile_info, fp, fc->caller == NULL ? NULL : fc->caller->func); #endif save_current_sctx = current_sctx; current_sctx = fp->uf_script_ctx; save_did_emsg = did_emsg; did_emsg = FALSE; if (default_arg_err && (fp->uf_flags & FC_ABORT)) did_emsg = TRUE; else if (islambda) { char_u *p = *(char_u **)fp->uf_lines.ga_data + 7; // A Lambda always has the command "return {expr}". It is much faster // to evaluate {expr} directly. ++ex_nesting_level; (void)eval1(&p, rettv, &EVALARG_EVALUATE); --ex_nesting_level; } else // call do_cmdline() to execute the lines do_cmdline(NULL, get_func_line, (void *)fc, DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); --RedrawingDisabled; // when the function was aborted because of an error, return -1 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { clear_tv(rettv); rettv->v_type = VAR_NUMBER; rettv->vval.v_number = -1; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) { ufunc_T *caller = fc->caller == NULL ? NULL : fc->caller->func; if (fp->uf_profiling || (caller != NULL && caller->uf_profiling)) profile_may_end_func(&profile_info, fp, caller); } #endif // when being verbose, mention the return value if (p_verbose >= 12) { ++no_wait_return; verbose_enter_scroll(); if (aborting()) smsg(_("%s aborted"), SOURCING_NAME); else if (fc->rettv->v_type == VAR_NUMBER) smsg(_("%s returning #%ld"), SOURCING_NAME, (long)fc->rettv->vval.v_number); else { char_u buf[MSG_BUF_LEN]; char_u numbuf2[NUMBUFLEN]; char_u *tofree; char_u *s; // The value may be very long. Skip the middle part, so that we // have some idea how it starts and ends. smsg() would always // truncate it at the end. Don't want errors such as E724 here. ++emsg_off; s = tv2string(fc->rettv, &tofree, numbuf2, 0); --emsg_off; if (s != NULL) { if (vim_strsize(s) > MSG_BUF_CLEN) { trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); s = buf; } smsg(_("%s returning %s"), SOURCING_NAME, s); vim_free(tofree); } } msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } ESTACK_CHECK_NOW estack_pop(); current_sctx = save_current_sctx; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) script_prof_restore(&profile_info.pi_wait_start); #endif if (using_sandbox) --sandbox; if (p_verbose >= 12 && SOURCING_NAME != NULL) { ++no_wait_return; verbose_enter_scroll(); smsg(_("continuing in %s"), SOURCING_NAME); msg_puts("\n"); // don't overwrite this either verbose_leave_scroll(); --no_wait_return; } did_emsg |= save_did_emsg; funcdepth_decrement(); for (i = 0; i < tv_to_free_len; ++i) clear_tv(tv_to_free[i]); cleanup_function_call(fc); } /* * Check the argument count for user function "fp". * Return FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise. */ int check_user_func_argcount(ufunc_T *fp, int argcount) { int regular_args = fp->uf_args.ga_len; if (argcount < regular_args - fp->uf_def_args.ga_len) return FCERR_TOOFEW; else if (!has_varargs(fp) && argcount > regular_args) return FCERR_TOOMANY; return FCERR_UNKNOWN; } /* * Call a user function after checking the arguments. */ int call_user_func_check( ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, funcexe_T *funcexe, dict_T *selfdict) { int error; if (fp->uf_flags & FC_RANGE && funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = TRUE; error = check_user_func_argcount(fp, argcount); if (error != FCERR_UNKNOWN) return error; if ((fp->uf_flags & FC_DICT) && selfdict == NULL) error = FCERR_DICT; else { int did_save_redo = FALSE; save_redo_T save_redo; /* * Call the user function. * Save and restore search patterns, script variables and * redo buffer. */ save_search_patterns(); if (!ins_compl_active()) { saveRedobuff(&save_redo); did_save_redo = TRUE; } ++fp->uf_calls; call_user_func(fp, argcount, argvars, rettv, funcexe, (fp->uf_flags & FC_DICT) ? selfdict : NULL); if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) // Function was unreferenced while being used, free it now. func_clear_free(fp, FALSE); if (did_save_redo) restoreRedobuff(&save_redo); restore_search_patterns(); error = FCERR_NONE; } return error; } static funccal_entry_T *funccal_stack = NULL; /* * Save the current function call pointer, and set it to NULL. * Used when executing autocommands and for ":source". */ void save_funccal(funccal_entry_T *entry) { entry->top_funccal = current_funccal; entry->next = funccal_stack; funccal_stack = entry; current_funccal = NULL; } void restore_funccal(void) { if (funccal_stack == NULL) iemsg("INTERNAL: restore_funccal()"); else { current_funccal = funccal_stack->top_funccal; funccal_stack = funccal_stack->next; } } funccall_T * get_current_funccal(void) { return current_funccal; } /* * Mark all functions of script "sid" as deleted. */ void delete_script_functions(int sid) { hashitem_T *hi; ufunc_T *fp; long_u todo = 1; char_u buf[30]; size_t len; buf[0] = K_SPECIAL; buf[1] = KS_EXTRA; buf[2] = (int)KE_SNR; sprintf((char *)buf + 3, "%d_", sid); len = STRLEN(buf); while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { fp = HI2UF(hi); if (STRNCMP(fp->uf_name, buf, len) == 0) { int changed = func_hashtab.ht_changed; fp->uf_flags |= FC_DEAD; if (fp->uf_calls > 0) { // Function is executing, don't free it but do remove // it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else { func_clear(fp, TRUE); // When clearing a function another function can be // cleared as a side effect. When that happens start // over. if (changed != func_hashtab.ht_changed) break; } } --todo; } } } #if defined(EXITFREE) || defined(PROTO) void free_all_functions(void) { hashitem_T *hi; ufunc_T *fp; long_u skipped = 0; long_u todo = 1; int changed; // Clean up the current_funccal chain and the funccal stack. while (current_funccal != NULL) { clear_tv(current_funccal->rettv); cleanup_function_call(current_funccal); if (current_funccal == NULL && funccal_stack != NULL) restore_funccal(); } // First clear what the functions contain. Since this may lower the // reference count of a function, it may also free a function and change // the hash table. Restart if that happens. while (todo > 0) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { // clear the def function index now fp = HI2UF(hi); fp->uf_flags &= ~FC_DEAD; fp->uf_def_status = UF_NOT_COMPILED; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. if (func_name_refcount(fp->uf_name)) ++skipped; else { changed = func_hashtab.ht_changed; func_clear(fp, TRUE); if (changed != func_hashtab.ht_changed) { skipped = 0; break; } } --todo; } } // Now actually free the functions. Need to start all over every time, // because func_free() may change the hash table. skipped = 0; while (func_hashtab.ht_used > skipped) { todo = func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0; ++hi) if (!HASHITEM_EMPTY(hi)) { --todo; // Only free functions that are not refcounted, those are // supposed to be freed when no longer referenced. fp = HI2UF(hi); if (func_name_refcount(fp->uf_name)) ++skipped; else { if (func_free(fp, FALSE) == OK) { skipped = 0; break; } // did not actually free it ++skipped; } } } if (skipped == 0) hash_clear(&func_hashtab); free_def_functions(); } #endif /* * Return TRUE if "name" looks like a builtin function name: starts with a * lower case letter and doesn't contain AUTOLOAD_CHAR or ':'. * "len" is the length of "name", or -1 for NUL terminated. */ int builtin_function(char_u *name, int len) { char_u *p; if (!ASCII_ISLOWER(name[0]) || name[1] == ':') return FALSE; p = vim_strchr(name, AUTOLOAD_CHAR); return p == NULL || (len > 0 && p > name + len); } int func_call( char_u *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv) { list_T *l = args->vval.v_list; listitem_T *item; typval_T argv[MAX_FUNC_ARGS + 1]; int argc = 0; int r = 0; CHECK_LIST_MATERIALIZE(l); FOR_ALL_LIST_ITEMS(l, item) { if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { emsg(_(e_too_many_arguments)); break; } // Make a copy of each argument. This is needed to be able to set // v_lock to VAR_FIXED in the copy without changing the original list. copy_tv(&item->li_tv, &argv[argc++]); } if (item == NULL) { funcexe_T funcexe; CLEAR_FIELD(funcexe); funcexe.fe_firstline = curwin->w_cursor.lnum; funcexe.fe_lastline = curwin->w_cursor.lnum; funcexe.fe_evaluate = TRUE; funcexe.fe_partial = partial; funcexe.fe_selfdict = selfdict; r = call_func(name, -1, rettv, argc, argv, &funcexe); } // Free the arguments. while (argc > 0) clear_tv(&argv[--argc]); return r; } static int callback_depth = 0; int get_callback_depth(void) { return callback_depth; } /* * Invoke call_func() with a callback. * Returns FAIL if the callback could not be called. */ int call_callback( callback_T *callback, int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { funcexe_T funcexe; int ret; if (callback->cb_name == NULL || *callback->cb_name == NUL) return FAIL; CLEAR_FIELD(funcexe); funcexe.fe_evaluate = TRUE; funcexe.fe_partial = callback->cb_partial; ++callback_depth; ret = call_func(callback->cb_name, len, rettv, argcount, argvars, &funcexe); --callback_depth; // When a :def function was called that uses :try an error would be turned // into an exception. Need to give the error here. if (need_rethrow && current_exception != NULL && trylevel == 0) { need_rethrow = FALSE; handle_did_throw(); } return ret; } /* * call the 'callback' function and return the result as a number. * Returns -2 when calling the function fails. Uses argv[0] to argv[argc - 1] * for the function arguments. argv[argc] should have type VAR_UNKNOWN. */ varnumber_T call_callback_retnr( callback_T *callback, int argcount, // number of "argvars" typval_T *argvars) // vars for arguments, must have "argcount" // PLUS ONE elements! { typval_T rettv; varnumber_T retval; if (call_callback(callback, 0, &rettv, argcount, argvars) == FAIL) return -2; retval = tv_get_number_chk(&rettv, NULL); clear_tv(&rettv); return retval; } /* * Give an error message for the result of a function. * Nothing if "error" is FCERR_NONE. */ void user_func_error(int error, char_u *name, funcexe_T *funcexe) { switch (error) { case FCERR_UNKNOWN: if (funcexe->fe_found_var) semsg(_(e_not_callable_type_str), name); else emsg_funcname(e_unknown_function_str, name); break; case FCERR_NOTMETHOD: emsg_funcname( N_(e_cannot_use_function_as_method_str), name); break; case FCERR_DELETED: emsg_funcname(e_function_was_deleted_str, name); break; case FCERR_TOOMANY: emsg_funcname(e_too_many_arguments_for_function_str, name); break; case FCERR_TOOFEW: emsg_funcname(e_not_enough_arguments_for_function_str, name); break; case FCERR_SCRIPT: emsg_funcname( e_using_sid_not_in_script_context_str, name); break; case FCERR_DICT: emsg_funcname(e_calling_dict_function_without_dictionary_str, name); break; } } /* * Call a function with its resolved parameters * * Return FAIL when the function can't be called, OK otherwise. * Also returns OK when an error was encountered while executing the function. */ int call_func( char_u *funcname, // name of the function int len, // length of "name" or -1 to use strlen() typval_T *rettv, // return value goes here int argcount_in, // number of "argvars" typval_T *argvars_in, // vars for arguments, must have "argcount" // PLUS ONE elements! funcexe_T *funcexe) // more arguments { int ret = FAIL; int error = FCERR_NONE; int i; ufunc_T *fp = NULL; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname = NULL; char_u *name = NULL; int argcount = argcount_in; typval_T *argvars = argvars_in; dict_T *selfdict = funcexe->fe_selfdict; typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" or // "funcexe->fe_basetv" is not NULL int argv_clear = 0; int argv_base = 0; partial_T *partial = funcexe->fe_partial; type_T check_type; type_T *check_type_args[MAX_FUNC_ARGS]; // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) // even when call_func() returns FAIL. rettv->v_type = VAR_UNKNOWN; if (partial != NULL) fp = partial->pt_func; if (fp == NULL) { // Make a copy of the name, if it comes from a funcref variable it // could be changed or deleted in the called function. name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname); if (name == NULL) return ret; fname = fname_trans_sid(name, fname_buf, &tofree, &error); } if (funcexe->fe_doesrange != NULL) *funcexe->fe_doesrange = FALSE; if (partial != NULL) { // When the function has a partial with a dict and there is a dict // argument, use the dict argument. That is backwards compatible. // When the dict was bound explicitly use the one from the partial. if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) selfdict = partial->pt_dict; if (error == FCERR_NONE && partial->pt_argc > 0) { for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear) { if (argv_clear + argcount_in >= MAX_FUNC_ARGS) { error = FCERR_TOOMANY; goto theend; } copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]); } for (i = 0; i < argcount_in; ++i) argv[i + argv_clear] = argvars_in[i]; argvars = argv; argcount = partial->pt_argc + argcount_in; if (funcexe->fe_check_type != NULL && funcexe->fe_check_type->tt_argcount != -1) { // Now funcexe->fe_check_type is missing the added arguments, // make a copy of the type with the correction. check_type = *funcexe->fe_check_type; funcexe->fe_check_type = &check_type; check_type.tt_args = check_type_args; CLEAR_FIELD(check_type_args); for (i = 0; i < check_type.tt_argcount; ++i) check_type_args[i + partial->pt_argc] = check_type.tt_args[i]; check_type.tt_argcount += partial->pt_argc; check_type.tt_min_argcount += partial->pt_argc; } } } if (error == FCERR_NONE && funcexe->fe_check_type != NULL && funcexe->fe_evaluate) { // Check that the argument types are OK for the types of the funcref. if (check_argument_types(funcexe->fe_check_type, argvars, argcount, (name != NULL) ? name : funcname) == FAIL) error = FCERR_OTHER; } if (error == FCERR_NONE && funcexe->fe_evaluate) { char_u *rfname = fname; int is_global = FALSE; // Skip "g:" before a function name. if (fp == NULL && fname[0] == 'g' && fname[1] == ':') { is_global = TRUE; rfname = fname + 2; } rettv->v_type = VAR_NUMBER; // default rettv is number zero rettv->vval.v_number = 0; error = FCERR_UNKNOWN; if (fp != NULL || !builtin_function(rfname, -1)) { /* * User defined function. */ if (fp == NULL) fp = find_func(rfname, is_global, NULL); // Trigger FuncUndefined event, may load the function. if (fp == NULL && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) && !aborting()) { // executed an autocommand, search for the function again fp = find_func(rfname, is_global, NULL); } // Try loading a package. if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) { // loaded a package, search for the function again fp = find_func(rfname, is_global, NULL); } if (fp == NULL) { char_u *p = untrans_function_name(rfname); // If using Vim9 script try not local to the script. // Don't do this if the name starts with "s:". if (p != NULL && (funcname[0] != 's' || funcname[1] != ':')) fp = find_func(p, is_global, NULL); } if (fp != NULL && (fp->uf_flags & FC_DELETED)) error = FCERR_DELETED; #ifdef FEAT_LUA else if (fp != NULL && (fp->uf_flags & FC_CFUNC)) { cfunc_T cb = fp->uf_cb; error = (*cb)(argcount, argvars, rettv, fp->uf_cb_state); } #endif else if (fp != NULL) { if (funcexe->fe_argv_func != NULL) // postponed filling in the arguments, do it now argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp->uf_args.ga_len); if (funcexe->fe_basetv != NULL) { // Method call: base->Method() mch_memmove(&argv[1], argvars, sizeof(typval_T) * argcount); argv[0] = *funcexe->fe_basetv; argcount++; argvars = argv; argv_base = 1; } error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict); } } else if (funcexe->fe_basetv != NULL) { /* * expr->method(): Find the method name in the table, call its * implementation with the base as one of the arguments. */ error = call_internal_method(fname, argcount, argvars, rettv, funcexe->fe_basetv); } else { /* * Find the function name in the table, call its implementation. */ error = call_internal_func(fname, argcount, argvars, rettv); } /* * The function call (or "FuncUndefined" autocommand sequence) might * have been aborted by an error, an interrupt, or an explicitly thrown * exception that has not been caught so far. This situation can be * tested for by calling aborting(). For an error in an internal * function or for the "E132" error in call_user_func(), however, the * throw point at which the "force_abort" flag (temporarily reset by * emsg()) is normally updated has not been reached yet. We need to * update that flag first to make aborting() reliable. */ update_force_abort(); } if (error == FCERR_NONE) ret = OK; theend: /* * Report an error unless the argument evaluation or function call has been * cancelled due to an aborting error, an interrupt, or an exception. */ if (!aborting()) { user_func_error(error, (name != NULL) ? name : funcname, funcexe); } // clear the copies made from the partial while (argv_clear > 0) clear_tv(&argv[--argv_clear + argv_base]); vim_free(tofree); vim_free(name); return ret; } char_u * printable_func_name(ufunc_T *fp) { return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name; } /* * List the head of the function: "function name(arg1, arg2)". */ static void list_func_head(ufunc_T *fp, int indent) { int j; msg_start(); if (indent) msg_puts(" "); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts("def "); else msg_puts("function "); msg_puts((char *)printable_func_name(fp)); msg_putchar('('); for (j = 0; j < fp->uf_args.ga_len; ++j) { if (j) msg_puts(", "); msg_puts((char *)FUNCARG(fp, j)); if (fp->uf_arg_types != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_arg_types[j], &tofree)); vim_free(tofree); } if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) { msg_puts(" = "); msg_puts(((char **)(fp->uf_def_args.ga_data)) [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]); } } if (fp->uf_varargs) { if (j) msg_puts(", "); msg_puts("..."); } if (fp->uf_va_name != NULL) { if (j) msg_puts(", "); msg_puts("..."); msg_puts((char *)fp->uf_va_name); if (fp->uf_va_type != NULL) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_va_type, &tofree)); vim_free(tofree); } } msg_putchar(')'); if (fp->uf_def_status != UF_NOT_COMPILED) { if (fp->uf_ret_type != &t_void) { char *tofree; msg_puts(": "); msg_puts(type_name(fp->uf_ret_type, &tofree)); vim_free(tofree); } } else if (fp->uf_flags & FC_ABORT) msg_puts(" abort"); if (fp->uf_flags & FC_RANGE) msg_puts(" range"); if (fp->uf_flags & FC_DICT) msg_puts(" dict"); if (fp->uf_flags & FC_CLOSURE) msg_puts(" closure"); msg_clr_eos(); if (p_verbose > 0) last_set_msg(fp->uf_script_ctx); } /* * Get a function name, translating "<SID>" and "<SNR>". * Also handles a Funcref in a List or Dictionary. * Returns the function name in allocated memory, or NULL for failure. * Set "*is_global" to TRUE when the function must be global, unless * "is_global" is NULL. * flags: * TFN_INT: internal function name OK * TFN_QUIET: be quiet * TFN_NO_AUTOLOAD: do not use script autoloading * TFN_NO_DEREF: do not dereference a Funcref * Advances "pp" to just after the function name (if no error). */ char_u * trans_function_name( char_u **pp, int *is_global, int skip, // only find the end, don't evaluate int flags, funcdict_T *fdp, // return: info about dictionary used partial_T **partial, // return: partial of a FuncRef type_T **type) // return: type of funcref if not NULL { char_u *name = NULL; char_u *start; char_u *end; int lead; char_u sid_buf[20]; int len; int extra = 0; lval_T lv; int vim9script; if (fdp != NULL) CLEAR_POINTER(fdp); start = *pp; // Check for hard coded <SNR>: already translated function ID (from a user // command). if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA && (*pp)[2] == (int)KE_SNR) { *pp += 3; len = get_id_len(pp) + 3; return vim_strnsave(start, len); } // A name starting with "<SID>" or "<SNR>" is local to a script. But // don't skip over "s:", get_lval() needs it for "s:dict.func". lead = eval_fname_script(start); if (lead > 2) start += lead; // Note that TFN_ flags use the same values as GLV_ flags. end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, lead > 2 ? 0 : FNE_CHECK_START); if (end == start) { if (!skip) emsg(_(e_function_name_required)); goto theend; } if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { /* * Report an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (end != NULL) semsg(_(e_invalid_argument_str), start); } else *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); goto theend; } if (lv.ll_tv != NULL) { if (fdp != NULL) { fdp->fd_dict = lv.ll_dict; fdp->fd_newkey = lv.ll_newkey; lv.ll_newkey = NULL; fdp->fd_di = lv.ll_di; } if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { name = vim_strsave(lv.ll_tv->vval.v_string); *pp = end; } else if (lv.ll_tv->v_type == VAR_PARTIAL && lv.ll_tv->vval.v_partial != NULL) { name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); *pp = end; if (partial != NULL) *partial = lv.ll_tv->vval.v_partial; } else { if (!skip && !(flags & TFN_QUIET) && (fdp == NULL || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) emsg(_(e_funcref_required)); else *pp = end; name = NULL; } goto theend; } if (lv.ll_name == NULL) { // Error found, but continue after the function name. *pp = end; goto theend; } // Check if the name is a Funcref. If so, use the value. if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); name = deref_func_name(lv.ll_exp_name, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == lv.ll_exp_name) name = NULL; } else if (!(flags & TFN_NO_DEREF)) { len = (int)(end - *pp); name = deref_func_name(*pp, &len, partial, type, flags & TFN_NO_AUTOLOAD, NULL); if (name == *pp) name = NULL; } if (name != NULL) { name = vim_strsave(name); *pp = end; if (STRNCMP(name, "<SNR>", 5) == 0) { // Change "<SNR>" to the byte sequence. name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); } goto theend; } if (lv.ll_exp_name != NULL) { len = (int)STRLEN(lv.ll_exp_name); if (lead <= 2 && lv.ll_name == lv.ll_exp_name && STRNCMP(lv.ll_name, "s:", 2) == 0) { // When there was "s:" already or the name expanded to get a // leading "s:" then remove it. lv.ll_name += 2; len -= 2; lead = 2; } } else { // skip over "s:" and "g:" if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { if (is_global != NULL && lv.ll_name[0] == 'g') *is_global = TRUE; lv.ll_name += 2; } len = (int)(end - lv.ll_name); } if (len <= 0) { if (!skip) emsg(_(e_function_name_required)); goto theend; } // In Vim9 script a user function is script-local by default, unless it // starts with a lower case character: dict.func(). vim9script = ASCII_ISUPPER(*start) && in_vim9script(); if (vim9script) { char_u *p; // SomeScript#func() is a global function. for (p = start; *p != NUL && *p != '('; ++p) if (*p == AUTOLOAD_CHAR) vim9script = FALSE; } /* * Copy the function name to allocated memory. * Accept <SID>name() inside a script, translate into <SNR>123_name(). * Accept <SNR>123_name() outside a script. */ if (skip) lead = 0; // do nothing else if (lead > 0 || vim9script) { if (!vim9script) lead = 3; if (vim9script || (lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) || eval_fname_sid(*pp)) { // It's script-local, "s:" or "<SID>" if (current_sctx.sc_sid <= 0) { emsg(_(e_using_sid_not_in_script_context)); goto theend; } sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid); if (vim9script) extra = 3 + (int)STRLEN(sid_buf); else lead += (int)STRLEN(sid_buf); } } else if (!(flags & TFN_INT) && (builtin_function(lv.ll_name, len) || (in_vim9script() && *lv.ll_name == '_'))) { semsg(_(e_function_name_must_start_with_capital_or_s_str), start); goto theend; } if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { char_u *cp = vim_strchr(lv.ll_name, ':'); if (cp != NULL && cp < end) { semsg(_(e_function_name_cannot_contain_colon_str), start); goto theend; } } name = alloc(len + lead + extra + 1); if (name != NULL) { if (!skip && (lead > 0 || vim9script)) { name[0] = K_SPECIAL; name[1] = KS_EXTRA; name[2] = (int)KE_SNR; if (vim9script || lead > 3) // If it's "<SID>" STRCPY(name + 3, sid_buf); } mch_memmove(name + lead + extra, lv.ll_name, (size_t)len); name[lead + extra + len] = NUL; } *pp = end; theend: clear_lval(&lv); return name; } /* * Assuming "name" is the result of trans_function_name() and it was prefixed * to use the script-local name, return the unmodified name (points into * "name"). Otherwise return NULL. * This can be used to first search for a script-local function and fall back * to the global function if not found. */ char_u * untrans_function_name(char_u *name) { char_u *p; if (*name == K_SPECIAL && in_vim9script()) { p = vim_strchr(name, '_'); if (p != NULL) return p + 1; } return NULL; } /* * If the 'funcname' starts with "s:" or "<SID>", then expands it to the * current script ID and returns the expanded function name. The caller should * free the returned name. If not called from a script context or the function * name doesn't start with these prefixes, then returns NULL. * This doesn't check whether the script-local function exists or not. */ char_u * get_scriptlocal_funcname(char_u *funcname) { char sid_buf[25]; int off; char_u *newname; if (funcname == NULL) return NULL; if (STRNCMP(funcname, "s:", 2) != 0 && STRNCMP(funcname, "<SID>", 5) != 0) // The function name is not a script-local function name return NULL; if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) { emsg(_(e_using_sid_not_in_script_context)); return NULL; } // Expand s: prefix into <SNR>nr_<name> vim_snprintf(sid_buf, sizeof(sid_buf), "<SNR>%ld_", (long)current_sctx.sc_sid); off = *funcname == 's' ? 2 : 5; newname = alloc(STRLEN(sid_buf) + STRLEN(funcname + off) + 1); if (newname == NULL) return NULL; STRCPY(newname, sid_buf); STRCAT(newname, funcname + off); return newname; } /* * Call trans_function_name(), except that a lambda is returned as-is. * Returns the name in allocated memory. */ char_u * save_function_name( char_u **name, int *is_global, int skip, int flags, funcdict_T *fudi) { char_u *p = *name; char_u *saved; if (STRNCMP(p, "<lambda>", 8) == 0) { p += 8; (void)getdigits(&p); saved = vim_strnsave(*name, p - *name); if (fudi != NULL) CLEAR_POINTER(fudi); } else saved = trans_function_name(&p, is_global, skip, flags, fudi, NULL, NULL); *name = p; return saved; } /* * List functions. When "regmatch" is NULL all of then. * Otherwise functions matching "regmatch". */ void list_functions(regmatch_T *regmatch) { int changed = func_hashtab.ht_changed; long_u todo = func_hashtab.ht_used; hashitem_T *hi; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { ufunc_T *fp = HI2UF(hi); --todo; if ((fp->uf_flags & FC_DEAD) == 0 && (regmatch == NULL ? !message_filtered(fp->uf_name) && !func_name_refcount(fp->uf_name) : !isdigit(*fp->uf_name) && vim_regexec(regmatch, fp->uf_name, 0))) { list_func_head(fp, FALSE); if (changed != func_hashtab.ht_changed) { emsg(_(e_function_list_was_modified)); return; } } } } } /* * ":function" also supporting nested ":def". * When "name_arg" is not NULL this is a nested function, using "name_arg" for * the function name. * "lines_to_free" is a list of strings to be freed later. * Returns a pointer to the function or NULL if no function defined. */ ufunc_T * define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free) { int j; int c; int saved_did_emsg; char_u *name = name_arg; int is_global = FALSE; char_u *p; char_u *arg; char_u *whitep; char_u *line_arg = NULL; garray_T newargs; garray_T argtypes; garray_T default_args; garray_T newlines; int varargs = FALSE; int flags = 0; char_u *ret_type = NULL; ufunc_T *fp = NULL; int fp_allocated = FALSE; int free_fp = FALSE; int overwrite = FALSE; dictitem_T *v; funcdict_T fudi; static int func_nr = 0; // number for nameless function int paren; hashitem_T *hi; linenr_T sourcing_lnum_top; int vim9script = in_vim9script(); imported_T *import = NULL; /* * ":function" without argument: list functions. */ if (ends_excmd2(eap->cmd, eap->arg)) { if (!eap->skip) list_functions(NULL); set_nextcmd(eap, eap->arg); return NULL; } /* * ":function /pat": list functions matching pattern. */ if (*eap->arg == '/') { p = skip_regexp(eap->arg + 1, '/', TRUE); if (!eap->skip) { regmatch_T regmatch; c = *p; *p = NUL; regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); *p = c; if (regmatch.regprog != NULL) { regmatch.rm_ic = p_ic; list_functions(&regmatch); vim_regfree(regmatch.regprog); } } if (*p == '/') ++p; set_nextcmd(eap, p); return NULL; } ga_init(&newargs); ga_init(&argtypes); ga_init(&default_args); /* * Get the function name. There are these situations: * func normal function name * "name" == func, "fudi.fd_dict" == NULL * dict.func new dictionary entry * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func * dict.func existing dict entry with a Funcref * "name" == func, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * dict.func existing dict entry that's not a Funcref * "name" == NULL, "fudi.fd_dict" set, * "fudi.fd_di" set, "fudi.fd_newkey" == NULL * s:func script-local function name * g:func global function name, same as "func" */ p = eap->arg; if (name_arg != NULL) { // nested function, argument is (args). paren = TRUE; CLEAR_FIELD(fudi); } else { name = save_function_name(&p, &is_global, eap->skip, TFN_NO_AUTOLOAD, &fudi); paren = (vim_strchr(p, '(') != NULL); if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { /* * Return on an invalid expression in braces, unless the expression * evaluation has been cancelled due to an aborting error, an * interrupt, or an exception. */ if (!aborting()) { if (!eap->skip && fudi.fd_newkey != NULL) semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); return NULL; } else eap->skip = TRUE; } } // An error in a function call during evaluation of an expression in magic // braces should not cause the function not to be defined. saved_did_emsg = did_emsg; did_emsg = FALSE; /* * ":function func" with only function name: list function. */ if (!paren) { if (!ends_excmd(*skipwhite(p))) { semsg(_(e_trailing_characters_str), p); goto ret_free; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (!eap->skip && !got_int) { fp = find_func(name, is_global, NULL); if (fp == NULL && ASCII_ISUPPER(*eap->arg)) { char_u *up = untrans_function_name(name); // With Vim9 script the name was made script-local, if not // found try again with the original name. if (up != NULL) fp = find_func(up, FALSE, NULL); } if (fp != NULL) { list_func_head(fp, TRUE); for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) { if (FUNCLINE(fp, j) == NULL) continue; msg_putchar('\n'); msg_outnum((long)(j + 1)); if (j < 9) msg_putchar(' '); if (j < 99) msg_putchar(' '); msg_prt_line(FUNCLINE(fp, j), FALSE); out_flush(); // show a line at a time ui_breakcheck(); } if (!got_int) { msg_putchar('\n'); if (fp->uf_def_status != UF_NOT_COMPILED) msg_puts(" enddef"); else msg_puts(" endfunction"); } } else emsg_funcname(e_undefined_function_str, eap->arg); } goto ret_free; } /* * ":function name(arg1, arg2)" Define function. */ p = skipwhite(p); if (*p != '(') { if (!eap->skip) { semsg(_(e_missing_paren_str), eap->arg); goto ret_free; } // attempt to continue by skipping some text if (vim_strchr(p, '(') != NULL) p = vim_strchr(p, '('); } if ((vim9script || eap->cmdidx == CMD_def) && VIM_ISWHITE(p[-1])) { semsg(_(e_no_white_space_allowed_before_str_str), "(", p - 1); goto ret_free; } // In Vim9 script only global functions can be redefined. if (vim9script && eap->forceit && !is_global) { emsg(_(e_no_bang_allowed)); goto ret_free; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (!eap->skip && name_arg == NULL) { // Check the name of the function. Unless it's a dictionary function // (that we are overwriting). if (name != NULL) arg = name; else arg = fudi.fd_newkey; if (arg != NULL && (fudi.fd_di == NULL || (fudi.fd_di->di_tv.v_type != VAR_FUNC && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) { char_u *name_base = arg; int i; if (*arg == K_SPECIAL) { name_base = vim_strchr(arg, '_'); if (name_base == NULL) name_base = arg + 3; else ++name_base; } for (i = 0; name_base[i] != NUL && (i == 0 ? eval_isnamec1(name_base[i]) : eval_isnamec(name_base[i])); ++i) ; if (name_base[i] != NUL) emsg_funcname(e_invalid_argument_str, arg); // In Vim9 script a function cannot have the same name as a // variable. if (vim9script && *arg == K_SPECIAL && eval_variable(name_base, (int)STRLEN(name_base), 0, NULL, NULL, EVAL_VAR_NOAUTOLOAD + EVAL_VAR_IMPORT + EVAL_VAR_NO_FUNC) == OK) { semsg(_(e_redefining_script_item_str), name_base); goto ret_free; } } // Disallow using the g: dict. if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) { emsg(_(e_cannot_use_g_here)); goto ret_free; } } // This may get more lines and make the pointers into the first line // invalid. ++p; if (get_function_args(&p, ')', &newargs, eap->cmdidx == CMD_def ? &argtypes : NULL, FALSE, NULL, &varargs, &default_args, eap->skip, eap, lines_to_free) == FAIL) goto errret_2; whitep = p; if (eap->cmdidx == CMD_def) { // find the return type: :def Func(): type if (*skipwhite(p) == ':') { if (*p != ':') { semsg(_(e_no_white_space_allowed_before_colon_str), p); p = skipwhite(p); } else if (!IS_WHITE_OR_NUL(p[1])) semsg(_(e_white_space_required_after_str_str), ":", p); ret_type = skipwhite(p + 1); p = skip_type(ret_type, FALSE); if (p > ret_type) { ret_type = vim_strnsave(ret_type, p - ret_type); whitep = p; p = skipwhite(p); } else { semsg(_(e_expected_type_str), ret_type); ret_type = NULL; } } p = skipwhite(p); } else // find extra arguments "range", "dict", "abort" and "closure" for (;;) { whitep = p; p = skipwhite(p); if (STRNCMP(p, "range", 5) == 0) { flags |= FC_RANGE; p += 5; } else if (STRNCMP(p, "dict", 4) == 0) { flags |= FC_DICT; p += 4; } else if (STRNCMP(p, "abort", 5) == 0) { flags |= FC_ABORT; p += 5; } else if (STRNCMP(p, "closure", 7) == 0) { flags |= FC_CLOSURE; p += 7; if (current_funccal == NULL) { emsg_funcname(e_closure_function_should_not_be_at_top_level, name == NULL ? (char_u *)"" : name); goto erret; } } else break; } // When there is a line break use what follows for the function body. // Makes 'exe "func Test()\n...\nendfunc"' work. if (*p == '\n') line_arg = p + 1; else if (*p != NUL && !(*p == '"' && (!vim9script || eap->cmdidx == CMD_function) && eap->cmdidx != CMD_def) && !(VIM_ISWHITE(*whitep) && *p == '#' && (vim9script || eap->cmdidx == CMD_def)) && !eap->skip && !did_emsg) semsg(_(e_trailing_characters_str), p); /* * Read the body of the function, until "}", ":endfunction" or ":enddef" is * found. */ if (KeyTyped) { // Check if the function already exists, don't let the user type the // whole function before telling him it doesn't work! For a script we // need to skip the body to be able to find what follows. if (!eap->skip && !eap->forceit) { if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) emsg(_(e_dictionary_entry_already_exists)); else if (name != NULL && find_func(name, is_global, NULL) != NULL) emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); } if (!eap->skip && did_emsg) goto erret; msg_putchar('\n'); // don't overwrite the function name cmdline_row = msg_row; } // Save the starting line number. sourcing_lnum_top = SOURCING_LNUM; // Do not define the function when getting the body fails and when // skipping. if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL || eap->skip) goto erret; /* * If there are no errors, add the function */ if (fudi.fd_dict == NULL) { hashtab_T *ht; v = find_var(name, &ht, TRUE); if (v != NULL && v->di_tv.v_type == VAR_FUNC) { emsg_funcname(e_function_name_conflicts_with_variable_str, name); goto erret; } fp = find_func_even_dead(name, is_global, NULL); if (vim9script) { char_u *uname = untrans_function_name(name); import = find_imported(uname == NULL ? name : uname, 0, NULL); } if (fp != NULL || import != NULL) { int dead = fp != NULL && (fp->uf_flags & FC_DEAD); // Function can be replaced with "function!" and when sourcing the // same script again, but only once. // A name that is used by an import can not be overruled. if (import != NULL || (!dead && !eap->forceit && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))) { SOURCING_LNUM = sourcing_lnum_top; if (vim9script) emsg_funcname(e_name_already_defined_str, name); else emsg_funcname(e_function_str_already_exists_add_bang_to_replace, name); goto erret; } if (fp->uf_calls > 0) { emsg_funcname( e_cannot_redefine_function_str_it_is_in_use, name); goto erret; } if (fp->uf_refcount > 1) { // This function is referenced somewhere, don't redefine it but // create a new one. --fp->uf_refcount; fp->uf_flags |= FC_REMOVED; fp = NULL; overwrite = TRUE; } else { char_u *exp_name = fp->uf_name_exp; // redefine existing function, keep the expanded name VIM_CLEAR(name); fp->uf_name_exp = NULL; func_clear_items(fp); fp->uf_name_exp = exp_name; fp->uf_flags &= ~FC_DEAD; #ifdef FEAT_PROFILE fp->uf_profiling = FALSE; fp->uf_prof_initialized = FALSE; #endif fp->uf_def_status = UF_NOT_COMPILED; } } } else { char numbuf[20]; fp = NULL; if (fudi.fd_newkey == NULL && !eap->forceit) { emsg(_(e_dictionary_entry_already_exists)); goto erret; } if (fudi.fd_di == NULL) { // Can't add a function to a locked dictionary if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) goto erret; } // Can't change an existing function if it is locked else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) goto erret; // Give the function a sequential number. Can only be used with a // Funcref! vim_free(name); sprintf(numbuf, "%d", ++func_nr); name = vim_strsave((char_u *)numbuf); if (name == NULL) goto erret; } if (fp == NULL) { if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { int slen, plen; char_u *scriptname; // Check that the autoload name matches the script name. j = FAIL; if (SOURCING_NAME != NULL) { scriptname = autoload_name(name); if (scriptname != NULL) { p = vim_strchr(scriptname, '/'); plen = (int)STRLEN(p); slen = (int)STRLEN(SOURCING_NAME); if (slen > plen && fnamecmp(p, SOURCING_NAME + slen - plen) == 0) j = OK; vim_free(scriptname); } } if (j == FAIL) { linenr_T save_lnum = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; semsg(_(e_function_name_does_not_match_script_file_name_str), name); SOURCING_LNUM = save_lnum; goto erret; } } fp = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (fp == NULL) goto erret; fp_allocated = TRUE; if (fudi.fd_dict != NULL) { if (fudi.fd_di == NULL) { // add new dict entry fudi.fd_di = dictitem_alloc(fudi.fd_newkey); if (fudi.fd_di == NULL) { vim_free(fp); fp = NULL; goto erret; } if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { vim_free(fudi.fd_di); vim_free(fp); fp = NULL; goto erret; } } else // overwrite existing dict entry clear_tv(&fudi.fd_di->di_tv); fudi.fd_di->di_tv.v_type = VAR_FUNC; fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); // behave like "dict" was used flags |= FC_DICT; } } fp->uf_args = newargs; fp->uf_def_args = default_args; fp->uf_ret_type = &t_any; fp->uf_func_type = &t_func_any; if (eap->cmdidx == CMD_def) { int lnum_save = SOURCING_LNUM; cstack_T *cstack = eap->cstack; fp->uf_def_status = UF_TO_BE_COMPILED; // error messages are for the first function line SOURCING_LNUM = sourcing_lnum_top; // The function may use script variables from the context. function_using_block_scopes(fp, cstack); if (parse_argument_types(fp, &argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } varargs = FALSE; // parse the return type, if any if (parse_return_type(fp, ret_type) == FAIL) { SOURCING_LNUM = lnum_save; free_fp = fp_allocated; goto erret; } SOURCING_LNUM = lnum_save; } else fp->uf_def_status = UF_NOT_COMPILED; if (fp_allocated) { // insert the new function in the function list set_ufunc_name(fp, name); if (overwrite) { hi = hash_find(&func_hashtab, name); hi->hi_key = UF2HIKEY(fp); } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { free_fp = TRUE; goto erret; } fp->uf_refcount = 1; } fp->uf_lines = newlines; newlines.ga_data = NULL; if ((flags & FC_CLOSURE) != 0) { if (register_closure(fp) == FAIL) goto erret; } else fp->uf_scoped = NULL; #ifdef FEAT_PROFILE if (prof_def_func()) func_do_profile(fp); #endif fp->uf_varargs = varargs; if (sandbox) flags |= FC_SANDBOX; if (vim9script && !ASCII_ISUPPER(*fp->uf_name)) flags |= FC_VIM9; fp->uf_flags = flags; fp->uf_calls = 0; fp->uf_cleared = FALSE; fp->uf_script_ctx = current_sctx; fp->uf_script_ctx_version = current_sctx.sc_version; fp->uf_script_ctx.sc_lnum += sourcing_lnum_top; if (is_export) { fp->uf_flags |= FC_EXPORT; // let ex_export() know the export worked. is_export = FALSE; } if (eap->cmdidx == CMD_def) set_function_type(fp); else if (fp->uf_script_ctx.sc_version == SCRIPT_VERSION_VIM9) // :func does not use Vim9 script syntax, even in a Vim9 script file fp->uf_script_ctx.sc_version = SCRIPT_VERSION_MAX; goto ret_free; erret: ga_clear_strings(&newargs); ga_clear_strings(&default_args); if (fp != NULL) { ga_init(&fp->uf_args); ga_init(&fp->uf_def_args); } errret_2: ga_clear_strings(&newlines); if (fp != NULL) VIM_CLEAR(fp->uf_arg_types); if (free_fp) { vim_free(fp); fp = NULL; } ret_free: ga_clear_strings(&argtypes); vim_free(fudi.fd_newkey); if (name != name_arg) vim_free(name); vim_free(ret_type); did_emsg |= saved_did_emsg; return fp; } /* * ":function" */ void ex_function(exarg_T *eap) { garray_T lines_to_free; ga_init2(&lines_to_free, sizeof(char_u *), 50); (void)define_function(eap, NULL, &lines_to_free); ga_clear_strings(&lines_to_free); } /* * :defcompile - compile all :def functions in the current script that need to * be compiled. Except dead functions. Doesn't do profiling. */ void ex_defcompile(exarg_T *eap UNUSED) { long todo = (long)func_hashtab.ht_used; int changed = func_hashtab.ht_changed; hashitem_T *hi; ufunc_T *ufunc; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; ufunc = HI2UF(hi); if (ufunc->uf_script_ctx.sc_sid == current_sctx.sc_sid && ufunc->uf_def_status == UF_TO_BE_COMPILED && (ufunc->uf_flags & FC_DEAD) == 0) { (void)compile_def_function(ufunc, FALSE, CT_NONE, NULL); if (func_hashtab.ht_changed != changed) { // a function has been added or removed, need to start over todo = (long)func_hashtab.ht_used; changed = func_hashtab.ht_changed; hi = func_hashtab.ht_array; --hi; } } } } } /* * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). * Return 2 if "p" starts with "s:". * Return 0 otherwise. */ int eval_fname_script(char_u *p) { // Use MB_STRICMP() because in Turkish comparing the "I" may not work with // the standard library function. if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) return 5; if (p[0] == 's' && p[1] == ':') return 2; return 0; } int translated_function_exists(char_u *name, int is_global) { if (builtin_function(name, -1)) return has_internal_func(name); return find_func(name, is_global, NULL) != NULL; } /* * Return TRUE when "ufunc" has old-style "..." varargs * or named varargs "...name: type". */ int has_varargs(ufunc_T *ufunc) { return ufunc->uf_varargs || ufunc->uf_va_name != NULL; } /* * Return TRUE if a function "name" exists. * If "no_defef" is TRUE, do not dereference a Funcref. */ int function_exists(char_u *name, int no_deref) { char_u *nm = name; char_u *p; int n = FALSE; int flag; int is_global = FALSE; flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; if (no_deref) flag |= TFN_NO_DEREF; p = trans_function_name(&nm, &is_global, FALSE, flag, NULL, NULL, NULL); nm = skipwhite(nm); // Only accept "funcname", "funcname ", "funcname (..." and // "funcname(...", not "funcname!...". if (p != NULL && (*nm == NUL || *nm == '(')) n = translated_function_exists(p, is_global); vim_free(p); return n; } #if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO) char_u * get_expanded_name(char_u *name, int check) { char_u *nm = name; char_u *p; int is_global = FALSE; p = trans_function_name(&nm, &is_global, FALSE, TFN_INT|TFN_QUIET, NULL, NULL, NULL); if (p != NULL && *nm == NUL && (!check || translated_function_exists(p, is_global))) return p; vim_free(p); return NULL; } #endif /* * Function given to ExpandGeneric() to obtain the list of user defined * function names. */ char_u * get_user_func_name(expand_T *xp, int idx) { static long_u done; static int changed; static hashitem_T *hi; ufunc_T *fp; if (idx == 0) { done = 0; hi = func_hashtab.ht_array; changed = func_hashtab.ht_changed; } if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) { if (done++ > 0) ++hi; while (HASHITEM_EMPTY(hi)) ++hi; fp = HI2UF(hi); // don't show dead, dict and lambda functions if ((fp->uf_flags & FC_DEAD) || (fp->uf_flags & FC_DICT) || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) return (char_u *)""; if (STRLEN(fp->uf_name) + 4 >= IOSIZE) return fp->uf_name; // prevents overflow cat_func_name(IObuff, fp); if (xp->xp_context != EXPAND_USER_FUNC && xp->xp_context != EXPAND_DISASSEMBLE) { STRCAT(IObuff, "("); if (!has_varargs(fp) && fp->uf_args.ga_len == 0) STRCAT(IObuff, ")"); } return IObuff; } return NULL; } /* * ":delfunction {name}" */ void ex_delfunction(exarg_T *eap) { ufunc_T *fp = NULL; char_u *p; char_u *name; funcdict_T fudi; int is_global = FALSE; p = eap->arg; name = trans_function_name(&p, &is_global, eap->skip, 0, &fudi, NULL, NULL); vim_free(fudi.fd_newkey); if (name == NULL) { if (fudi.fd_dict != NULL && !eap->skip) emsg(_(e_funcref_required)); return; } if (!ends_excmd(*skipwhite(p))) { vim_free(name); semsg(_(e_trailing_characters_str), p); return; } set_nextcmd(eap, p); if (eap->nextcmd != NULL) *p = NUL; if (numbered_function(name) && fudi.fd_dict == NULL) { if (!eap->skip) semsg(_(e_invalid_argument_str), eap->arg); vim_free(name); return; } if (!eap->skip) fp = find_func(name, is_global, NULL); vim_free(name); if (!eap->skip) { if (fp == NULL) { if (!eap->forceit) semsg(_(e_unknown_function_str), eap->arg); return; } if (fp->uf_calls > 0) { semsg(_(e_cannot_delete_function_str_it_is_in_use), eap->arg); return; } if (fp->uf_flags & FC_VIM9) { semsg(_(e_cannot_delete_vim9_script_function_str), eap->arg); return; } if (fudi.fd_dict != NULL) { // Delete the dict item that refers to the function, it will // invoke func_unref() and possibly delete the function. dictitem_remove(fudi.fd_dict, fudi.fd_di); } else { // A normal function (not a numbered function or lambda) has a // refcount of 1 for the entry in the hashtable. When deleting // it and the refcount is more than one, it should be kept. // A numbered function and lambda should be kept if the refcount is // one or more. if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { // Function is still referenced somewhere. Don't free it but // do remove it from the hashtable. if (func_remove(fp)) fp->uf_refcount--; } else func_clear_free(fp, FALSE); } } } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. */ void func_unref(char_u *name) { ufunc_T *fp = NULL; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp == NULL && numbered_function(name)) { #ifdef EXITFREE if (!entered_free_all_mem) #endif internal_error("func_unref()"); } func_ptr_unref(fp); } /* * Unreference a Function: decrement the reference count and free it when it * becomes zero. * Also when it becomes one and uf_partial points to the function. */ void func_ptr_unref(ufunc_T *fp) { if (fp != NULL && (--fp->uf_refcount <= 0 || (fp->uf_refcount == 1 && fp->uf_partial != NULL && fp->uf_partial->pt_refcount <= 1 && fp->uf_partial->pt_func == fp))) { // Only delete it when it's not being used. Otherwise it's done // when "uf_calls" becomes zero. if (fp->uf_calls == 0) func_clear_free(fp, FALSE); } } /* * Count a reference to a Function. */ void func_ref(char_u *name) { ufunc_T *fp; if (name == NULL || !func_name_refcount(name)) return; fp = find_func(name, FALSE, NULL); if (fp != NULL) ++fp->uf_refcount; else if (numbered_function(name)) // Only give an error for a numbered function. // Fail silently, when named or lambda function isn't found. internal_error("func_ref()"); } /* * Count a reference to a Function. */ void func_ptr_ref(ufunc_T *fp) { if (fp != NULL) ++fp->uf_refcount; } /* * Return TRUE if items in "fc" do not have "copyID". That means they are not * referenced from anywhere that is in use. */ static int can_free_funccal(funccall_T *fc, int copyID) { return (fc->l_varlist.lv_copyID != copyID && fc->l_vars.dv_copyID != copyID && fc->l_avars.dv_copyID != copyID && fc->fc_copyID != copyID); } /* * ":return [expr]" */ void ex_return(exarg_T *eap) { char_u *arg = eap->arg; typval_T rettv; int returning = FALSE; evalarg_T evalarg; if (current_funccal == NULL) { emsg(_(e_return_not_inside_function)); return; } init_evalarg(&evalarg); evalarg.eval_flags = eap->skip ? 0 : EVAL_EVALUATE; if (eap->skip) ++emsg_skip; eap->nextcmd = NULL; if ((*arg != NUL && *arg != '|' && *arg != '\n') && eval0(arg, &rettv, eap, &evalarg) != FAIL) { if (!eap->skip) returning = do_return(eap, FALSE, TRUE, &rettv); else clear_tv(&rettv); } // It's safer to return also on error. else if (!eap->skip) { // In return statement, cause_abort should be force_abort. update_force_abort(); /* * Return unless the expression evaluation has been cancelled due to an * aborting error, an interrupt, or an exception. */ if (!aborting()) returning = do_return(eap, FALSE, TRUE, NULL); } // When skipping or the return gets pending, advance to the next command // in this line (!returning). Otherwise, ignore the rest of the line. // Following lines will be ignored by get_func_line(). if (returning) eap->nextcmd = NULL; else if (eap->nextcmd == NULL) // no argument set_nextcmd(eap, arg); if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); } /* * ":1,25call func(arg1, arg2)" function call. */ void ex_call(exarg_T *eap) { char_u *arg = eap->arg; char_u *startarg; char_u *name; char_u *tofree; int len; typval_T rettv; linenr_T lnum; int doesrange; int failed = FALSE; funcdict_T fudi; partial_T *partial = NULL; evalarg_T evalarg; type_T *type = NULL; int found_var = FALSE; fill_evalarg_from_eap(&evalarg, eap, eap->skip); if (eap->skip) { // trans_function_name() doesn't work well when skipping, use eval0() // instead to skip to any following command, e.g. for: // :if 0 | call dict.foo().bar() | endif ++emsg_skip; if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) clear_tv(&rettv); --emsg_skip; clear_evalarg(&evalarg, eap); return; } tofree = trans_function_name(&arg, NULL, eap->skip, TFN_INT, &fudi, &partial, in_vim9script() ? &type : NULL); if (fudi.fd_newkey != NULL) { // Still need to give an error message for missing key. semsg(_(e_key_not_present_in_dictionary), fudi.fd_newkey); vim_free(fudi.fd_newkey); } if (tofree == NULL) return; // Increase refcount on dictionary, it could get deleted when evaluating // the arguments. if (fudi.fd_dict != NULL) ++fudi.fd_dict->dv_refcount; // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its // contents. For VAR_PARTIAL get its partial, unless we already have one // from trans_function_name(). len = (int)STRLEN(tofree); name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, in_vim9script() && type == NULL ? &type : NULL, FALSE, &found_var); // Skip white space to allow ":call func ()". Not good, but required for // backward compatibility. startarg = skipwhite(arg); if (*startarg != '(') { semsg(_(e_missing_parenthesis_str), eap->arg); goto end; } if (in_vim9script() && startarg > arg) { semsg(_(e_no_white_space_allowed_before_str_str), "(", eap->arg); goto end; } /* * When skipping, evaluate the function once, to find the end of the * arguments. * When the function takes a range, this is discovered after the first * call, and the loop is broken. */ if (eap->skip) { ++emsg_skip; lnum = eap->line2; // do it once, also with an invalid range } else lnum = eap->line1; for ( ; lnum <= eap->line2; ++lnum) { funcexe_T funcexe; if (!eap->skip && eap->addr_count > 0) { if (lnum > curbuf->b_ml.ml_line_count) { // If the function deleted lines or switched to another buffer // the line number may become invalid. emsg(_(e_invalid_range)); break; } curwin->w_cursor.lnum = lnum; curwin->w_cursor.col = 0; curwin->w_cursor.coladd = 0; } arg = startarg; CLEAR_FIELD(funcexe); funcexe.fe_firstline = eap->line1; funcexe.fe_lastline = eap->line2; funcexe.fe_doesrange = &doesrange; funcexe.fe_evaluate = !eap->skip; funcexe.fe_partial = partial; funcexe.fe_selfdict = fudi.fd_dict; funcexe.fe_check_type = type; funcexe.fe_found_var = found_var; rettv.v_type = VAR_UNKNOWN; // clear_tv() uses this if (get_func_tv(name, -1, &rettv, &arg, &evalarg, &funcexe) == FAIL) { failed = TRUE; break; } if (has_watchexpr()) dbg_check_breakpoint(eap); // Handle a function returning a Funcref, Dictionary or List. if (handle_subscript(&arg, NULL, &rettv, eap->skip ? NULL : &EVALARG_EVALUATE, TRUE) == FAIL) { failed = TRUE; break; } clear_tv(&rettv); if (doesrange || eap->skip) break; // Stop when immediately aborting on error, or when an interrupt // occurred or an exception was thrown but not caught. // get_func_tv() returned OK, so that the check for trailing // characters below is executed. if (aborting()) break; } if (eap->skip) --emsg_skip; clear_evalarg(&evalarg, eap); // When inside :try we need to check for following "| catch" or "| endtry". // Not when there was an error, but do check if an exception was thrown. if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) { // Check for trailing illegal characters and a following command. arg = skipwhite(arg); if (!ends_excmd2(eap->arg, arg)) { if (!failed && !aborting()) { emsg_severe = TRUE; semsg(_(e_trailing_characters_str), arg); } } else set_nextcmd(eap, arg); } end: dict_unref(fudi.fd_dict); vim_free(tofree); } /* * Return from a function. Possibly makes the return pending. Also called * for a pending return at the ":endtry" or after returning from an extra * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set * when called due to a ":return" command. "rettv" may point to a typval_T * with the return rettv. Returns TRUE when the return can be carried out, * FALSE when the return gets pending. */ int do_return( exarg_T *eap, int reanimate, int is_cmd, void *rettv) { int idx; cstack_T *cstack = eap->cstack; if (reanimate) // Undo the return. current_funccal->returned = FALSE; /* * Cleanup (and inactivate) conditionals, but stop when a try conditional * not in its finally clause (which then is to be executed next) is found. * In this case, make the ":return" pending for execution at the ":endtry". * Otherwise, return normally. */ idx = cleanup_conditionals(eap->cstack, 0, TRUE); if (idx >= 0) { cstack->cs_pending[idx] = CSTP_RETURN; if (!is_cmd && !reanimate) // A pending return again gets pending. "rettv" points to an // allocated variable with the rettv of the original ":return"'s // argument if present or is NULL else. cstack->cs_rettv[idx] = rettv; else { // When undoing a return in order to make it pending, get the stored // return rettv. if (reanimate) rettv = current_funccal->rettv; if (rettv != NULL) { // Store the value of the pending return. if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; else emsg(_(e_out_of_memory)); } else cstack->cs_rettv[idx] = NULL; if (reanimate) { // The pending return value could be overwritten by a ":return" // without argument in a finally clause; reset the default // return value. current_funccal->rettv->v_type = VAR_NUMBER; current_funccal->rettv->vval.v_number = 0; } } report_make_pending(CSTP_RETURN, rettv); } else { current_funccal->returned = TRUE; // If the return is carried out now, store the return value. For // a return immediately after reanimation, the value is already // there. if (!reanimate && rettv != NULL) { clear_tv(current_funccal->rettv); *current_funccal->rettv = *(typval_T *)rettv; if (!is_cmd) vim_free(rettv); } } return idx < 0; } /* * Free the variable with a pending return value. */ void discard_pending_return(void *rettv) { free_tv((typval_T *)rettv); } /* * Generate a return command for producing the value of "rettv". The result * is an allocated string. Used by report_pending() for verbose messages. */ char_u * get_return_cmd(void *rettv) { char_u *s = NULL; char_u *tofree = NULL; char_u numbuf[NUMBUFLEN]; if (rettv != NULL) s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); if (s == NULL) s = (char_u *)""; STRCPY(IObuff, ":return "); STRNCPY(IObuff + 8, s, IOSIZE - 8); if (STRLEN(s) + 8 >= IOSIZE) STRCPY(IObuff + IOSIZE - 4, "..."); vim_free(tofree); return vim_strsave(IObuff); } /* * Get next function line. * Called by do_cmdline() to get the next line. * Returns allocated string, or NULL for end of function. */ char_u * get_func_line( int c UNUSED, void *cookie, int indent UNUSED, getline_opt_T options UNUSED) { funccall_T *fcp = (funccall_T *)cookie; ufunc_T *fp = fcp->func; char_u *retval; garray_T *gap; // growarray with function lines // If breakpoints have been added/deleted need to check for it. if (fcp->dbg_tick != debug_tick) { fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_end(cookie); #endif gap = &fp->uf_lines; if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned) retval = NULL; else { // Skip NULL lines (continuation lines). while (fcp->linenr < gap->ga_len && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) ++fcp->linenr; if (fcp->linenr >= gap->ga_len) retval = NULL; else { retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); SOURCING_LNUM = fcp->linenr; #ifdef FEAT_PROFILE if (do_profiling == PROF_YES) func_line_start(cookie, SOURCING_LNUM); #endif } } // Did we encounter a breakpoint? if (fcp->breakpoint != 0 && fcp->breakpoint <= SOURCING_LNUM) { dbg_breakpoint(fp->uf_name, SOURCING_LNUM); // Find next breakpoint. fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, SOURCING_LNUM); fcp->dbg_tick = debug_tick; } return retval; } /* * Return TRUE if the currently active function should be ended, because a * return was encountered or an error occurred. Used inside a ":while". */ int func_has_ended(void *cookie) { funccall_T *fcp = (funccall_T *)cookie; // Ignore the "abort" flag if the abortion behavior has been changed due to // an error inside a try conditional. return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) || fcp->returned); } /* * return TRUE if cookie indicates a function which "abort"s on errors. */ int func_has_abort( void *cookie) { return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; } /* * Turn "dict.Func" into a partial for "Func" bound to "dict". * Don't do this when "Func" is already a partial that was bound * explicitly (pt_auto is FALSE). * Changes "rettv" in-place. * Returns the updated "selfdict_in". */ dict_T * make_partial(dict_T *selfdict_in, typval_T *rettv) { char_u *fname; char_u *tofree = NULL; ufunc_T *fp; char_u fname_buf[FLEN_FIXED + 1]; int error; dict_T *selfdict = selfdict_in; if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) fp = rettv->vval.v_partial->pt_func; else { fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string : rettv->vval.v_partial->pt_name; // Translate "s:func" to the stored function name. fname = fname_trans_sid(fname, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); vim_free(tofree); } if (fp != NULL && (fp->uf_flags & FC_DICT)) { partial_T *pt = ALLOC_CLEAR_ONE(partial_T); if (pt != NULL) { pt->pt_refcount = 1; pt->pt_dict = selfdict; pt->pt_auto = TRUE; selfdict = NULL; if (rettv->v_type == VAR_FUNC) { // Just a function: Take over the function name and use // selfdict. pt->pt_name = rettv->vval.v_string; } else { partial_T *ret_pt = rettv->vval.v_partial; int i; // Partial: copy the function name, use selfdict and copy // args. Can't take over name or args, the partial might // be referenced elsewhere. if (ret_pt->pt_name != NULL) { pt->pt_name = vim_strsave(ret_pt->pt_name); func_ref(pt->pt_name); } else { pt->pt_func = ret_pt->pt_func; func_ptr_ref(pt->pt_func); } if (ret_pt->pt_argc > 0) { pt->pt_argv = ALLOC_MULT(typval_T, ret_pt->pt_argc); if (pt->pt_argv == NULL) // out of memory: drop the arguments pt->pt_argc = 0; else { pt->pt_argc = ret_pt->pt_argc; for (i = 0; i < pt->pt_argc; i++) copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); } } partial_unref(ret_pt); } rettv->v_type = VAR_PARTIAL; rettv->vval.v_partial = pt; } } return selfdict; } /* * Return the name of the executed function. */ char_u * func_name(void *cookie) { return ((funccall_T *)cookie)->func->uf_name; } /* * Return the address holding the next breakpoint line for a funccall cookie. */ linenr_T * func_breakpoint(void *cookie) { return &((funccall_T *)cookie)->breakpoint; } /* * Return the address holding the debug tick for a funccall cookie. */ int * func_dbg_tick(void *cookie) { return &((funccall_T *)cookie)->dbg_tick; } /* * Return the nesting level for a funccall cookie. */ int func_level(void *cookie) { return ((funccall_T *)cookie)->level; } /* * Return TRUE when a function was ended by a ":return" command. */ int current_func_returned(void) { return current_funccal->returned; } int free_unref_funccal(int copyID, int testing) { int did_free = FALSE; int did_free_funccal = FALSE; funccall_T *fc, **pfc; for (pfc = &previous_funccal; *pfc != NULL; ) { if (can_free_funccal(*pfc, copyID)) { fc = *pfc; *pfc = fc->caller; free_funccal_contents(fc); did_free = TRUE; did_free_funccal = TRUE; } else pfc = &(*pfc)->caller; } if (did_free_funccal) // When a funccal was freed some more items might be garbage // collected, so run again. (void)garbage_collect(testing); return did_free; } /* * Get function call environment based on backtrace debug level */ static funccall_T * get_funccal(void) { int i; funccall_T *funccal; funccall_T *temp_funccal; funccal = current_funccal; if (debug_backtrace_level > 0) { for (i = 0; i < debug_backtrace_level; i++) { temp_funccal = funccal->caller; if (temp_funccal) funccal = temp_funccal; else // backtrace level overflow. reset to max debug_backtrace_level = i; } } return funccal; } /* * Return the hashtable used for local variables in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_local_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars.dv_hashtab; } /* * Return the l: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_local_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_vars_var; } /* * Return the hashtable used for argument in the current funccal. * Return NULL if there is no current funccal. */ hashtab_T * get_funccal_args_ht() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars.dv_hashtab; } /* * Return the a: scope variable. * Return NULL if there is no current funccal. */ dictitem_T * get_funccal_args_var() { if (current_funccal == NULL || current_funccal->l_vars.dv_refcount == 0) return NULL; return &get_funccal()->l_avars_var; } /* * List function variables, if there is a function. */ void list_func_vars(int *first) { if (current_funccal != NULL && current_funccal->l_vars.dv_refcount > 0) list_hashtable_vars(&current_funccal->l_vars.dv_hashtab, "l:", FALSE, first); } /* * If "ht" is the hashtable for local variables in the current funccal, return * the dict that contains it. * Otherwise return NULL. */ dict_T * get_current_funccal_dict(hashtab_T *ht) { if (current_funccal != NULL && ht == &current_funccal->l_vars.dv_hashtab) return &current_funccal->l_vars; return NULL; } /* * Search hashitem in parent scope. */ hashitem_T * find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) { funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; hashitem_T *hi = NULL; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope, which can be referenced from a lambda. current_funccal = current_funccal->func->uf_scoped; while (current_funccal != NULL) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { hi = hash_find(ht, varname); if (!HASHITEM_EMPTY(hi)) { *pht = ht; break; } } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return hi; } /* * Search variable in parent scope. */ dictitem_T * find_var_in_scoped_ht(char_u *name, int no_autoload) { dictitem_T *v = NULL; funccall_T *old_current_funccal = current_funccal; hashtab_T *ht; char_u *varname; if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) return NULL; // Search in parent scope which is possible to reference from lambda current_funccal = current_funccal->func->uf_scoped; while (current_funccal) { ht = find_var_ht(name, &varname); if (ht != NULL && *varname != NUL) { v = find_var_in_ht(ht, *name, varname, no_autoload); if (v != NULL) break; } if (current_funccal == current_funccal->func->uf_scoped) break; current_funccal = current_funccal->func->uf_scoped; } current_funccal = old_current_funccal; return v; } /* * Set "copyID + 1" in previous_funccal and callers. */ int set_ref_in_previous_funccal(int copyID) { funccall_T *fc; for (fc = previous_funccal; fc != NULL; fc = fc->caller) { fc->fc_copyID = copyID + 1; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID + 1, NULL)) return TRUE; } return FALSE; } static int set_ref_in_funccal(funccall_T *fc, int copyID) { if (fc->fc_copyID != copyID) { fc->fc_copyID = copyID; if (set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL) || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL) || set_ref_in_list_items(&fc->l_varlist, copyID, NULL) || set_ref_in_func(NULL, fc->func, copyID)) return TRUE; } return FALSE; } /* * Set "copyID" in all local vars and arguments in the call stack. */ int set_ref_in_call_stack(int copyID) { funccall_T *fc; funccal_entry_T *entry; for (fc = current_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; // Also go through the funccal_stack. for (entry = funccal_stack; entry != NULL; entry = entry->next) for (fc = entry->top_funccal; fc != NULL; fc = fc->caller) if (set_ref_in_funccal(fc, copyID)) return TRUE; return FALSE; } /* * Set "copyID" in all functions available by name. */ int set_ref_in_functions(int copyID) { int todo; hashitem_T *hi = NULL; ufunc_T *fp; todo = (int)func_hashtab.ht_used; for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { if (!HASHITEM_EMPTY(hi)) { --todo; fp = HI2UF(hi); if (!func_name_refcount(fp->uf_name) && set_ref_in_func(NULL, fp, copyID)) return TRUE; } } return FALSE; } /* * Set "copyID" in all function arguments. */ int set_ref_in_func_args(int copyID) { int i; for (i = 0; i < funcargs.ga_len; ++i) if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i], copyID, NULL, NULL)) return TRUE; return FALSE; } /* * Mark all lists and dicts referenced through function "name" with "copyID". * Returns TRUE if setting references failed somehow. */ int set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) { ufunc_T *fp = fp_in; funccall_T *fc; int error = FCERR_NONE; char_u fname_buf[FLEN_FIXED + 1]; char_u *tofree = NULL; char_u *fname; int abort = FALSE; if (name == NULL && fp_in == NULL) return FALSE; if (fp_in == NULL) { fname = fname_trans_sid(name, fname_buf, &tofree, &error); fp = find_func(fname, FALSE, NULL); } if (fp != NULL) { for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) abort = abort || set_ref_in_funccal(fc, copyID); } vim_free(tofree); return abort; } #endif // FEAT_EVAL
lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; char_u *line_to_free = NULL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL) { if (cmdline != line_to_free) vim_free(cmdline); goto erret; } // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; if (cmdline == line_to_free) line_to_free = NULL; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; vim_free(line_to_free); ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; }
lambda_function_body( char_u **arg, typval_T *rettv, evalarg_T *evalarg, garray_T *newargs, garray_T *argtypes, int varargs, garray_T *default_args, char_u *ret_type) { int evaluate = (evalarg->eval_flags & EVAL_EVALUATE); garray_T *gap = &evalarg->eval_ga; garray_T *freegap = &evalarg->eval_freega; ufunc_T *ufunc = NULL; exarg_T eap; garray_T newlines; char_u *cmdline = NULL; int ret = FAIL; partial_T *pt; char_u *name; int lnum_save = -1; linenr_T sourcing_lnum_top = SOURCING_LNUM; if (!ends_excmd2(*arg, skipwhite(*arg + 1))) { semsg(_(e_trailing_characters_str), *arg + 1); return FAIL; } CLEAR_FIELD(eap); eap.cmdidx = CMD_block; eap.forceit = FALSE; eap.cmdlinep = &cmdline; eap.skip = !evaluate; if (evalarg->eval_cctx != NULL) fill_exarg_from_cctx(&eap, evalarg->eval_cctx); else { eap.getline = evalarg->eval_getline; eap.cookie = evalarg->eval_cookie; } ga_init2(&newlines, (int)sizeof(char_u *), 10); if (get_function_body(&eap, &newlines, NULL, &evalarg->eval_tofree_ga) == FAIL) goto erret; // When inside a lambda must add the function lines to evalarg.eval_ga. evalarg->eval_break_count += newlines.ga_len; if (gap->ga_itemsize > 0) { int idx; char_u *last; size_t plen; char_u *pnl; for (idx = 0; idx < newlines.ga_len; ++idx) { char_u *p = skipwhite(((char_u **)newlines.ga_data)[idx]); if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; // Going to concatenate the lines after parsing. For an empty or // comment line use an empty string. // Insert NL characters at the start of each line, the string will // be split again later in .get_lambda_tv(). if (*p == NUL || vim9_comment_start(p)) p = (char_u *)""; plen = STRLEN(p); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, p, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (ga_grow(gap, 1) == FAIL || ga_grow(freegap, 1) == FAIL) goto erret; if (eap.nextcmd != NULL) // more is following after the "}", which was skipped last = cmdline; else // nothing is following the "}" last = (char_u *)"}"; plen = STRLEN(last); pnl = vim_strnsave((char_u *)"\n", plen + 1); if (pnl != NULL) mch_memmove(pnl + 1, last, plen + 1); ((char_u **)gap->ga_data)[gap->ga_len++] = pnl; ((char_u **)freegap->ga_data)[freegap->ga_len++] = pnl; } if (eap.nextcmd != NULL) { garray_T *tfgap = &evalarg->eval_tofree_ga; // Something comes after the "}". *arg = eap.nextcmd; // "arg" points into cmdline, need to keep the line and free it later. if (ga_grow(tfgap, 1) == OK) { ((char_u **)(tfgap->ga_data))[tfgap->ga_len++] = cmdline; evalarg->eval_using_cmdline = TRUE; } } else *arg = (char_u *)""; if (!evaluate) { ret = OK; goto erret; } name = get_lambda_name(); ufunc = alloc_clear(offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); if (ufunc == NULL) goto erret; set_ufunc_name(ufunc, name); if (hash_add(&func_hashtab, UF2HIKEY(ufunc)) == FAIL) goto erret; ufunc->uf_flags = FC_LAMBDA; ufunc->uf_refcount = 1; ufunc->uf_args = *newargs; newargs->ga_data = NULL; ufunc->uf_def_args = *default_args; default_args->ga_data = NULL; ufunc->uf_func_type = &t_func_any; // error messages are for the first function line lnum_save = SOURCING_LNUM; SOURCING_LNUM = sourcing_lnum_top; // parse argument types if (parse_argument_types(ufunc, argtypes, varargs) == FAIL) { SOURCING_LNUM = lnum_save; goto erret; } // parse the return type, if any if (parse_return_type(ufunc, ret_type) == FAIL) goto erret; pt = ALLOC_CLEAR_ONE(partial_T); if (pt == NULL) goto erret; pt->pt_func = ufunc; pt->pt_refcount = 1; ufunc->uf_lines = newlines; newlines.ga_data = NULL; if (sandbox) ufunc->uf_flags |= FC_SANDBOX; if (!ASCII_ISUPPER(*ufunc->uf_name)) ufunc->uf_flags |= FC_VIM9; ufunc->uf_script_ctx = current_sctx; ufunc->uf_script_ctx_version = current_sctx.sc_version; ufunc->uf_script_ctx.sc_lnum += sourcing_lnum_top; set_function_type(ufunc); function_using_block_scopes(ufunc, evalarg->eval_cstack); rettv->vval.v_partial = pt; rettv->v_type = VAR_PARTIAL; ufunc = NULL; ret = OK; erret: if (lnum_save >= 0) SOURCING_LNUM = lnum_save; ga_clear_strings(&newlines); if (newargs != NULL) ga_clear_strings(newargs); ga_clear_strings(default_args); if (ufunc != NULL) { func_clear(ufunc, TRUE); func_free(ufunc, TRUE); } return ret; }
{'added': [(169, ' * Get a next line, store it in "eap" if appropriate and put the line in'), (170, ' * "lines_to_free" to free the line later.'), (175, '\tgarray_T\t*lines_to_free,'), (187, '\tif (lines_to_free->ga_len > 0'), (188, '\t\t&& *eap->cmdlinep == ((char_u **)lines_to_free->ga_data)'), (189, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (191, '\tga_add_string(lines_to_free, theline);'), (214, ' garray_T\t*lines_to_free)'), (245, '\t char_u *theline = get_function_line(eap, lines_to_free, 0,'), (681, '\tgarray_T *lines_to_free)'), (748, '\t theline = get_function_line(eap, lines_to_free, indent,'), (858, '\t\t\t// change "eap->cmdlinep" to point to the last fetched'), (859, '\t\t\t// line.'), (861, '\t\t\tif (lines_to_free->ga_len > 0'), (862, '\t\t\t\t&& *eap->cmdlinep !='), (863, '\t\t\t\t\t ((char_u **)lines_to_free->ga_data)'), (864, '\t\t\t\t\t\t [lines_to_free->ga_len - 1])'), (866, '\t\t\t // *cmdlinep will be freed later, thus remove the'), (867, '\t\t\t // line from lines_to_free.'), (869, '\t\t\t *eap->cmdlinep = ((char_u **)lines_to_free->ga_data)'), (870, '\t\t\t\t\t\t [lines_to_free->ga_len - 1];'), (871, '\t\t\t --lines_to_free->ga_len;'), (1153, ' if (get_function_body(&eap, &newlines, NULL,'), (1154, '\t\t\t\t\t &evalarg->eval_tofree_ga) == FAIL)'), (3960, ' * "lines_to_free" is a list of strings to be freed later.'), (3964, 'define_function(exarg_T *eap, char_u *name_arg, garray_T *lines_to_free)'), (4233, '\t\t\t eap, lines_to_free) == FAIL)'), (4343, ' if (get_function_body(eap, &newlines, line_arg, lines_to_free) == FAIL'), (4649, ' garray_T lines_to_free;'), (4651, ' ga_init2(&lines_to_free, sizeof(char_u *), 50);'), (4652, ' (void)define_function(eap, NULL, &lines_to_free);'), (4653, ' ga_clear_strings(&lines_to_free);')], 'deleted': [(169, ' * Get a next line, store it in "eap" if appropriate and use "line_to_free" to'), (170, ' * handle freeing the line later.'), (175, '\tchar_u\t\t**line_to_free,'), (187, '\tif (*eap->cmdlinep == *line_to_free)'), (189, '\tvim_free(*line_to_free);'), (190, '\t*line_to_free = theline;'), (213, ' char_u\t**line_to_free)'), (244, '\t char_u *theline = get_function_line(eap, line_to_free, 0,'), (680, '\tchar_u\t **line_to_free)'), (747, '\t theline = get_function_line(eap, line_to_free, indent,'), (857, '\t\t\t// change "eap->cmdlinep".'), (859, '\t\t\tif (*line_to_free != NULL'), (860, '\t\t\t\t\t && *eap->cmdlinep != *line_to_free)'), (863, '\t\t\t *eap->cmdlinep = *line_to_free;'), (864, '\t\t\t *line_to_free = NULL;'), (1121, ' char_u\t*line_to_free = NULL;'), (1147, ' if (get_function_body(&eap, &newlines, NULL, &line_to_free) == FAIL)'), (1148, ' {'), (1149, '\tif (cmdline != line_to_free)'), (1150, '\t vim_free(cmdline);'), (1152, ' }'), (1211, '\t if (cmdline == line_to_free)'), (1212, '\t\tline_to_free = NULL;'), (1281, ' vim_free(line_to_free);'), (3963, 'define_function(exarg_T *eap, char_u *name_arg, char_u **line_to_free)'), (4232, '\t\t\t eap, line_to_free) == FAIL)'), (4342, ' if (get_function_body(eap, &newlines, line_arg, line_to_free) == FAIL'), (4648, ' char_u *line_to_free = NULL;'), (4650, ' (void)define_function(eap, NULL, &line_to_free);'), (4651, ' vim_free(line_to_free);')]}
32
30
4,372
24,654
https://github.com/vim/vim
CVE-2022-0156
['CWE-416']
ip6_output.c
__ip6_append_data
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/net/ipv4/ip_output.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/bpf-cgroup.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> #include <net/l3mdev.h> #include <net/lwtunnel.h> static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; struct in6_addr *nexthop; int ret; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) && ((mroute6_socket(net, skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len); if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <= IPV6_ADDR_SCOPE_NODELOCAL && !(dev->flags & IFF_LOOPBACK)) { kfree_skb(skb); return 0; } } if (lwtunnel_xmit_redirect(dst->lwtstate)) { int res = lwtunnel_xmit(skb); if (res < 0 || res == LWTUNNEL_XMIT_DONE) return res; } rcu_read_lock_bh(); nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr); neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false); if (!IS_ERR(neigh)) { sock_confirm_neigh(skb, neigh); ret = neigh_output(neigh, skb); rcu_read_unlock_bh(); return ret; } rcu_read_unlock_bh(); IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb) { int ret; ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb); if (ret) { kfree_skb(skb); return ret; } if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb)) || (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size)) return ip6_fragment(net, sk, skb, ip6_finish_output2); else return ip6_finish_output2(net, sk, skb); } int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) * Note : socket lock is not held for SYNACK packets, but might be modified * by calls to skb_set_owner_w() and ipv6_local_error(), * which are using proper atomic operations or spinlocks. */ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, __u32 mark, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } consume_skb(skb); skb = skb2; /* skb_set_owner_w() changes sk->sk_wmem_alloc atomically, * it is safe to call in our context (socket lock not held) */ skb_set_owner_w(skb, (struct sock *)sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop, &fl6->saddr); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out((struct sock *)sk, skb); if (unlikely(!skb)) return 0; /* hooks should never assume socket lock is held. * we promote our socket to non const */ return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, (struct sock *)sk, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; /* ipv6_local_error() does not require socket lock, * we promote our socket to non const */ ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { return dst_output(net, sk, skb); } static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst) { unsigned int mtu; struct inet6_dev *idev; if (dst_metric_locked(dst, RTAX_MTU)) { mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; } mtu = IPV6_MIN_MTU; rcu_read_lock(); idev = __in6_dev_get(dst->dev); if (idev) mtu = idev->cnf.mtu6; rcu_read_unlock(); return mtu; } static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu)) return false; return true; } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb->pkt_type != PACKET_HOST) goto drop; if (unlikely(skb->sk)) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) { if (ip6_call_ra_chain(skb, ntohs(opt->ra))) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if (net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct inet_peer *peer; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(peer, 1*HZ)) ndisc_send_redirect(skb, target); if (peer) inet_putpeer(peer); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = ip6_dst_mtu_forward(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (ip6_pkt_too_big(skb, mtu)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); __IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, net, NULL, skb, skb->dev, dst->dev, ip6_forward_finish); error: __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); } int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int (*output)(struct net *, struct sock *, struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; err = ip6_find_1stfragopt(skb, &prevhdr); if (err < 0) goto fail; hlen = err; nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu)) goto fail_toobig; if (IP6CB(skb)->frag_max_size) { if (IP6CB(skb)->frag_max_size > mtu) goto fail_toobig; /* don't send fragments larger than what we received */ mtu = IP6CB(skb)->frag_max_size; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < hlen + sizeof(struct frag_hdr) + 8) goto fail_toobig; mtu -= hlen + sizeof(struct frag_hdr); frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr); if (skb->ip_summed == CHECKSUM_PARTIAL && (err = skb_checksum_help(skb))) goto fail; hroom = LL_RESERVED_SPACE(rt->dst.dev); if (skb_has_frag_list(skb)) { unsigned int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb) || skb_headroom(skb) < (hroom + sizeof(struct frag_hdr))) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr))) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); fh->identification = frag_id; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(net, sk, skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { u8 *fragnexthdr_offset; len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* Allocate buffer */ frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC); if (!frag) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); fragnexthdr_offset = skb_network_header(frag); fragnexthdr_offset += prevhdr - skb_network_header(skb); *fragnexthdr_offset = NEXTHDR_FRAGMENT; /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(net, sk, frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail_toobig: if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); err = -EMSGSIZE; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) && (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; struct rt6_info *rt; #endif int err; int flags = 0; /* The correct way to handle this would be to do * ip6_route_get_saddr, and then ip6_route_output; however, * the route-specific preferred source forces the * ip6_route_output call _before_ ip6_route_get_saddr. * * In source specific routing (no src=any default route), * ip6_route_output will fail given src=any saddr, though, so * that's why we try it again later. */ if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) { struct rt6_info *rt; bool had_dst = *dst != NULL; if (!had_dst) *dst = ip6_route_output(net, sk, fl6); rt = (*dst)->error ? NULL : (struct rt6_info *)*dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; /* If we had an erroneous initial result, pretend it * never existed and let the SA-enabled version take * over. */ if (!had_dst && (*dst)->error) { dst_release(*dst); *dst = NULL; } if (fl6->flowi6_oif) flags |= RT6_LOOKUP_F_IFACE; } if (!*dst) *dst = ip6_route_output_flags(net, sk, fl6, flags); err = (*dst)->error; if (err) goto out_err_release; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rt = (struct rt6_info *) *dst; rcu_read_lock_bh(); n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr)); err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0; rcu_read_unlock_bh(); if (err) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); err = (*dst)->error; if (err) goto out_err_release; } } #endif if (ipv6_addr_v4mapped(&fl6->saddr) && !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) { err = -EAFNOSUPPORT; goto out_err_release; } return 0; out_err_release: dst_release(*dst); *dst = NULL; if (err == -ENETUNREACH) IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES); return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(net, sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); dst = ip6_sk_dst_check(sk, dst, fl6); if (!dst) dst = ip6_dst_lookup_flow(sk, fl6, final_dst); return dst; } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int exthdrlen, int transhdrlen, int mtu, unsigned int flags, const struct flowi6 *fl6) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ skb = skb_peek_tail(queue); if (!skb) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (!skb) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_set_network_header(skb, exthdrlen); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->csum = 0; if (flags & MSG_CONFIRM) skb_set_dst_pending_confirm(skb, 1); __skb_queue_tail(queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk), &fl6->daddr, &fl6->saddr); append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (!skb) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork, struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6, struct rt6_info *rt, struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); unsigned int mtu; struct ipv6_txoptions *opt = ipc6->opt; /* * setup for corking */ if (opt) { if (WARN_ON(v6_cork->opt)) return -EINVAL; v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation); if (unlikely(!v6_cork->opt)) return -ENOBUFS; v6_cork->opt->tot_len = opt->tot_len; v6_cork->opt->opt_flen = opt->opt_flen; v6_cork->opt->opt_nflen = opt->opt_nflen; v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !v6_cork->opt->dst0opt) return -ENOBUFS; v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !v6_cork->opt->dst1opt) return -ENOBUFS; v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !v6_cork->opt->hopopt) return -ENOBUFS; v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !v6_cork->opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->base.dst = &rt->dst; cork->fl.u.ip6 = *fl6; v6_cork->hop_limit = ipc6->hlimit; v6_cork->tclass = ipc6->tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); else mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } cork->base.fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->base.flags |= IPCORK_ALLFRAG; cork->base.length = 0; return 0; } static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((((length + fragheaderlen) > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; kfree_skb(skb); goto error; } else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); int exthdrlen; int err; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ err = ip6_setup_cork(sk, &inet->cork, &np->cork, ipc6, rt, fl6); if (err) return err; exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; } else { fl6 = &inet->cork.fl.u.ip6; transhdrlen = 0; } return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base, &np->cork, sk_page_frag(sk), getfrag, from, length, transhdrlen, flags, ipc6, sockc); } EXPORT_SYMBOL_GPL(ip6_append_data); static void ip6_cork_release(struct inet_cork_full *cork, struct inet6_cork *v6_cork) { if (v6_cork->opt) { kfree(v6_cork->opt->dst0opt); kfree(v6_cork->opt->dst1opt); kfree(v6_cork->opt->hopopt); kfree(v6_cork->opt->srcrt); kfree(v6_cork->opt); v6_cork->opt = NULL; } if (cork->base.dst) { dst_release(cork->base.dst); cork->base.dst = NULL; cork->base.flags &= ~IPCORK_ALLFRAG; } memset(&cork->fl, 0, sizeof(cork->fl)); } struct sk_buff *__ip6_make_skb(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = v6_cork->opt; struct rt6_info *rt = (struct rt6_info *)cork->base.dst; struct flowi6 *fl6 = &cork->fl.u.ip6; unsigned char proto = fl6->flowi6_proto; skb = __skb_dequeue(queue); if (!skb) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ skb->ignore_df = ip6_sk_ignore_df(sk); *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, v6_cork->tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->hop_limit = v6_cork->hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } ip6_cork_release(cork, v6_cork); out: return skb; } int ip6_send_skb(struct sk_buff *skb) { struct net *net = sock_net(skb->sk); struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); int err; err = ip6_local_out(net, skb->sk, skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); } return err; } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; skb = ip6_finish_skb(sk); if (!skb) return 0; return ip6_send_skb(skb); } EXPORT_SYMBOL_GPL(ip6_push_pending_frames); static void __ip6_flush_pending_frames(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(cork, v6_cork); } void ip6_flush_pending_frames(struct sock *sk) { __ip6_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork, &inet6_sk(sk)->cork); } EXPORT_SYMBOL_GPL(ip6_flush_pending_frames); struct sk_buff *ip6_make_skb(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_cork_full cork; struct inet6_cork v6_cork; struct sk_buff_head queue; int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.base.flags = 0; cork.base.addr = 0; cork.base.opt = NULL; v6_cork.opt = NULL; err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6); if (err) return ERR_PTR(err); if (ipc6->dontfrag < 0) ipc6->dontfrag = inet6_sk(sk)->dontfrag; err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork, &current->task_frag, getfrag, from, length + exthdrlen, transhdrlen + exthdrlen, flags, ipc6, sockc); if (err) { __ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork); return ERR_PTR(err); } return __ip6_make_skb(sk, &queue, &cork, &v6_cork); }
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/net/ipv4/ip_output.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/bpf-cgroup.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> #include <net/l3mdev.h> #include <net/lwtunnel.h> static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; struct in6_addr *nexthop; int ret; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) && ((mroute6_socket(net, skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len); if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <= IPV6_ADDR_SCOPE_NODELOCAL && !(dev->flags & IFF_LOOPBACK)) { kfree_skb(skb); return 0; } } if (lwtunnel_xmit_redirect(dst->lwtstate)) { int res = lwtunnel_xmit(skb); if (res < 0 || res == LWTUNNEL_XMIT_DONE) return res; } rcu_read_lock_bh(); nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr); neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false); if (!IS_ERR(neigh)) { sock_confirm_neigh(skb, neigh); ret = neigh_output(neigh, skb); rcu_read_unlock_bh(); return ret; } rcu_read_unlock_bh(); IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb) { int ret; ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb); if (ret) { kfree_skb(skb); return ret; } if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb)) || (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size)) return ip6_fragment(net, sk, skb, ip6_finish_output2); else return ip6_finish_output2(net, sk, skb); } int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) * Note : socket lock is not held for SYNACK packets, but might be modified * by calls to skb_set_owner_w() and ipv6_local_error(), * which are using proper atomic operations or spinlocks. */ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, __u32 mark, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } consume_skb(skb); skb = skb2; /* skb_set_owner_w() changes sk->sk_wmem_alloc atomically, * it is safe to call in our context (socket lock not held) */ skb_set_owner_w(skb, (struct sock *)sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop, &fl6->saddr); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out((struct sock *)sk, skb); if (unlikely(!skb)) return 0; /* hooks should never assume socket lock is held. * we promote our socket to non const */ return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, (struct sock *)sk, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; /* ipv6_local_error() does not require socket lock, * we promote our socket to non const */ ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { return dst_output(net, sk, skb); } static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst) { unsigned int mtu; struct inet6_dev *idev; if (dst_metric_locked(dst, RTAX_MTU)) { mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; } mtu = IPV6_MIN_MTU; rcu_read_lock(); idev = __in6_dev_get(dst->dev); if (idev) mtu = idev->cnf.mtu6; rcu_read_unlock(); return mtu; } static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu)) return false; return true; } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb->pkt_type != PACKET_HOST) goto drop; if (unlikely(skb->sk)) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) { if (ip6_call_ra_chain(skb, ntohs(opt->ra))) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if (net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct inet_peer *peer; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(peer, 1*HZ)) ndisc_send_redirect(skb, target); if (peer) inet_putpeer(peer); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = ip6_dst_mtu_forward(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (ip6_pkt_too_big(skb, mtu)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); __IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, net, NULL, skb, skb->dev, dst->dev, ip6_forward_finish); error: __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); } int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int (*output)(struct net *, struct sock *, struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; err = ip6_find_1stfragopt(skb, &prevhdr); if (err < 0) goto fail; hlen = err; nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu)) goto fail_toobig; if (IP6CB(skb)->frag_max_size) { if (IP6CB(skb)->frag_max_size > mtu) goto fail_toobig; /* don't send fragments larger than what we received */ mtu = IP6CB(skb)->frag_max_size; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < hlen + sizeof(struct frag_hdr) + 8) goto fail_toobig; mtu -= hlen + sizeof(struct frag_hdr); frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr); if (skb->ip_summed == CHECKSUM_PARTIAL && (err = skb_checksum_help(skb))) goto fail; hroom = LL_RESERVED_SPACE(rt->dst.dev); if (skb_has_frag_list(skb)) { unsigned int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb) || skb_headroom(skb) < (hroom + sizeof(struct frag_hdr))) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr))) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); fh->identification = frag_id; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(net, sk, skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { u8 *fragnexthdr_offset; len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* Allocate buffer */ frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC); if (!frag) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); fragnexthdr_offset = skb_network_header(frag); fragnexthdr_offset += prevhdr - skb_network_header(skb); *fragnexthdr_offset = NEXTHDR_FRAGMENT; /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(net, sk, frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail_toobig: if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); err = -EMSGSIZE; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) && (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; struct rt6_info *rt; #endif int err; int flags = 0; /* The correct way to handle this would be to do * ip6_route_get_saddr, and then ip6_route_output; however, * the route-specific preferred source forces the * ip6_route_output call _before_ ip6_route_get_saddr. * * In source specific routing (no src=any default route), * ip6_route_output will fail given src=any saddr, though, so * that's why we try it again later. */ if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) { struct rt6_info *rt; bool had_dst = *dst != NULL; if (!had_dst) *dst = ip6_route_output(net, sk, fl6); rt = (*dst)->error ? NULL : (struct rt6_info *)*dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; /* If we had an erroneous initial result, pretend it * never existed and let the SA-enabled version take * over. */ if (!had_dst && (*dst)->error) { dst_release(*dst); *dst = NULL; } if (fl6->flowi6_oif) flags |= RT6_LOOKUP_F_IFACE; } if (!*dst) *dst = ip6_route_output_flags(net, sk, fl6, flags); err = (*dst)->error; if (err) goto out_err_release; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rt = (struct rt6_info *) *dst; rcu_read_lock_bh(); n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr)); err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0; rcu_read_unlock_bh(); if (err) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); err = (*dst)->error; if (err) goto out_err_release; } } #endif if (ipv6_addr_v4mapped(&fl6->saddr) && !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) { err = -EAFNOSUPPORT; goto out_err_release; } return 0; out_err_release: dst_release(*dst); *dst = NULL; if (err == -ENETUNREACH) IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES); return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(net, sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); dst = ip6_sk_dst_check(sk, dst, fl6); if (!dst) dst = ip6_dst_lookup_flow(sk, fl6, final_dst); return dst; } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int exthdrlen, int transhdrlen, int mtu, unsigned int flags, const struct flowi6 *fl6) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ skb = skb_peek_tail(queue); if (!skb) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (!skb) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_set_network_header(skb, exthdrlen); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->csum = 0; if (flags & MSG_CONFIRM) skb_set_dst_pending_confirm(skb, 1); __skb_queue_tail(queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk), &fl6->daddr, &fl6->saddr); append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (!skb) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork, struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6, struct rt6_info *rt, struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); unsigned int mtu; struct ipv6_txoptions *opt = ipc6->opt; /* * setup for corking */ if (opt) { if (WARN_ON(v6_cork->opt)) return -EINVAL; v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation); if (unlikely(!v6_cork->opt)) return -ENOBUFS; v6_cork->opt->tot_len = opt->tot_len; v6_cork->opt->opt_flen = opt->opt_flen; v6_cork->opt->opt_nflen = opt->opt_nflen; v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !v6_cork->opt->dst0opt) return -ENOBUFS; v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !v6_cork->opt->dst1opt) return -ENOBUFS; v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !v6_cork->opt->hopopt) return -ENOBUFS; v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !v6_cork->opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->base.dst = &rt->dst; cork->fl.u.ip6 = *fl6; v6_cork->hop_limit = ipc6->hlimit; v6_cork->tclass = ipc6->tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); else mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } cork->base.fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->base.flags |= IPCORK_ALLFRAG; cork->base.length = 0; return 0; } static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((((length + fragheaderlen) > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; goto error; } if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); int exthdrlen; int err; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ err = ip6_setup_cork(sk, &inet->cork, &np->cork, ipc6, rt, fl6); if (err) return err; exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; } else { fl6 = &inet->cork.fl.u.ip6; transhdrlen = 0; } return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base, &np->cork, sk_page_frag(sk), getfrag, from, length, transhdrlen, flags, ipc6, sockc); } EXPORT_SYMBOL_GPL(ip6_append_data); static void ip6_cork_release(struct inet_cork_full *cork, struct inet6_cork *v6_cork) { if (v6_cork->opt) { kfree(v6_cork->opt->dst0opt); kfree(v6_cork->opt->dst1opt); kfree(v6_cork->opt->hopopt); kfree(v6_cork->opt->srcrt); kfree(v6_cork->opt); v6_cork->opt = NULL; } if (cork->base.dst) { dst_release(cork->base.dst); cork->base.dst = NULL; cork->base.flags &= ~IPCORK_ALLFRAG; } memset(&cork->fl, 0, sizeof(cork->fl)); } struct sk_buff *__ip6_make_skb(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = v6_cork->opt; struct rt6_info *rt = (struct rt6_info *)cork->base.dst; struct flowi6 *fl6 = &cork->fl.u.ip6; unsigned char proto = fl6->flowi6_proto; skb = __skb_dequeue(queue); if (!skb) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ skb->ignore_df = ip6_sk_ignore_df(sk); *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, v6_cork->tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->hop_limit = v6_cork->hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } ip6_cork_release(cork, v6_cork); out: return skb; } int ip6_send_skb(struct sk_buff *skb) { struct net *net = sock_net(skb->sk); struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); int err; err = ip6_local_out(net, skb->sk, skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); } return err; } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; skb = ip6_finish_skb(sk); if (!skb) return 0; return ip6_send_skb(skb); } EXPORT_SYMBOL_GPL(ip6_push_pending_frames); static void __ip6_flush_pending_frames(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(cork, v6_cork); } void ip6_flush_pending_frames(struct sock *sk) { __ip6_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork, &inet6_sk(sk)->cork); } EXPORT_SYMBOL_GPL(ip6_flush_pending_frames); struct sk_buff *ip6_make_skb(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_cork_full cork; struct inet6_cork v6_cork; struct sk_buff_head queue; int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.base.flags = 0; cork.base.addr = 0; cork.base.opt = NULL; v6_cork.opt = NULL; err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6); if (err) return ERR_PTR(err); if (ipc6->dontfrag < 0) ipc6->dontfrag = inet6_sk(sk)->dontfrag; err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork, &current->task_frag, getfrag, from, length + exthdrlen, transhdrlen + exthdrlen, flags, ipc6, sockc); if (err) { __ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork); return ERR_PTR(err); } return __ip6_make_skb(sk, &queue, &cork, &v6_cork); }
static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((((length + fragheaderlen) > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; kfree_skb(skb); goto error; } else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; }
static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((((length + fragheaderlen) > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; goto error; } if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; }
{'added': [(1469, '\t\t\tcopy = datalen - transhdrlen - fraggap;'), (1470, '\t\t\tif (copy < 0) {'), (1471, '\t\t\t\terr = -EINVAL;'), (1472, '\t\t\t\tgoto error;'), (1473, '\t\t\t}'), (1523, '\t\t\tif (copy > 0 &&'), (1524, '\t\t\t getfrag(from, data + transhdrlen, offset,'), (1525, '\t\t\t\t copy, fraggap, skb) < 0) {')], 'deleted': [(1518, '\t\t\tcopy = datalen - transhdrlen - fraggap;'), (1519, ''), (1520, '\t\t\tif (copy < 0) {'), (1521, '\t\t\t\terr = -EINVAL;'), (1522, '\t\t\t\tkfree_skb(skb);'), (1523, '\t\t\t\tgoto error;'), (1524, '\t\t\t} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {')]}
8
7
1,281
8,797
https://github.com/torvalds/linux
CVE-2017-9242
['CWE-20']
sock.c
sock_setsockopt
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/capability.h> #include <linux/errno.h> #include <linux/errqueue.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <linux/prefetch.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/sock_diag.h> #include <linux/filter.h> #include <net/sock_reuseport.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif #include <net/busy_poll.h> static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); /** * sk_ns_capable - General socket capability test * @sk: Socket to use a capability on or through * @user_ns: The user namespace of the capability to use * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in the user * namespace @user_ns. */ bool sk_ns_capable(const struct sock *sk, struct user_namespace *user_ns, int cap) { return file_ns_capable(sk->sk_socket->file, user_ns, cap) && ns_capable(user_ns, cap); } EXPORT_SYMBOL(sk_ns_capable); /** * sk_capable - Socket global capability test * @sk: Socket to use a capability on or through * @cap: The global capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in all user * namespaces. */ bool sk_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, &init_user_ns, cap); } EXPORT_SYMBOL(sk_capable); /** * sk_net_capable - Network namespace socket capability test * @sk: Socket to use a capability on or through * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was created * and the current process has the capability @cap over the network namespace * the socket is a member of. */ bool sk_net_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, sock_net(sk)->user_ns, cap); } EXPORT_SYMBOL(sk_net_capable); /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_VSOCK" , "sk_lock-AF_KCM" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_VSOCK" ,"slock-AF_KCM" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_VSOCK" , "clock-AF_KCM" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; EXPORT_SYMBOL(sysctl_wmem_max); __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; EXPORT_SYMBOL(sysctl_rmem_max); __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); int sysctl_tstamp_allow_data __read_mostly = 1; struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE; EXPORT_SYMBOL_GPL(memalloc_socks); /** * sk_set_memalloc - sets %SOCK_MEMALLOC * @sk: socket to set it on * * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. * It's the responsibility of the admin to adjust min_free_kbytes * to meet the requirements */ void sk_set_memalloc(struct sock *sk) { sock_set_flag(sk, SOCK_MEMALLOC); sk->sk_allocation |= __GFP_MEMALLOC; static_key_slow_inc(&memalloc_socks); } EXPORT_SYMBOL_GPL(sk_set_memalloc); void sk_clear_memalloc(struct sock *sk) { sock_reset_flag(sk, SOCK_MEMALLOC); sk->sk_allocation &= ~__GFP_MEMALLOC; static_key_slow_dec(&memalloc_socks); /* * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward * progress of swapping. SOCK_MEMALLOC may be cleared while * it has rmem allocations due to the last swapfile being deactivated * but there is a risk that the socket is unusable due to exceeding * the rmem limits. Reclaim the reserves and obey rmem limits again. */ sk_mem_reclaim(sk); } EXPORT_SYMBOL_GPL(sk_clear_memalloc); int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) { int ret; unsigned long pflags = current->flags; /* these should have been dropped before queueing */ BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); current->flags |= PF_MEMALLOC; ret = sk->sk_backlog_rcv(sk, skb); tsk_restore_flags(current, pflags, PF_MEMALLOC); return ret; } EXPORT_SYMBOL(__sk_backlog_rcv); static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", __func__, current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n", warncomm, name); warned++; } } static bool sock_needs_netstamp(const struct sock *sk) { switch (sk->sk_family) { case AF_UNSPEC: case AF_UNIX: return false; default: return true; } } static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (sock_needs_netstamp(sk) && !(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } if (!sk_rmem_schedule(sk, skb, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); sock_skb_set_dropcount(sk, skb); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(__sock_queue_rcv_skb); int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; err = sk_filter(sk, skb); if (err) return err; return __sock_queue_rcv_skb(sk, skb); } EXPORT_SYMBOL(sock_queue_rcv_skb); int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested, unsigned int trim_cap, bool refcounted) { int rc = NET_RX_SUCCESS; if (sk_filter_trim_cap(sk, skb, trim_cap)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: if (refcounted) sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(__sk_receive_skb); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_setbindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static int sock_getbindtodevice(struct sock *sk, char __user *optval, int __user *optlen, int len) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; if (sk->sk_bound_dev_if == 0) { len = 0; goto zero; } ret = -EINVAL; if (len < IFNAMSIZ) goto out; ret = netdev_get_name(net, devname, sk->sk_bound_dev_if); if (ret) goto out; len = strlen(devname) + 1; ret = -EFAULT; if (copy_to_user(optval, devname, len)) goto out; zero: ret = -EFAULT; if (put_user(len, optlen)) goto out; ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } bool sk_mc_loop(struct sock *sk) { if (dev_recursion_level()) return false; if (!sk) return true; switch (sk->sk_family) { case AF_INET: return inet_sk(sk)->mc_loop; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return inet6_sk(sk)->mc_loop; #endif } WARN_ON(1); return true; } EXPORT_SYMBOL(sk_mc_loop); /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); static void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = from_kuid_munged(current_ns, cred->euid); ucred->gid = from_kgid_munged(current_ns, cred->egid); } } int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_REUSEPORT: v.val = sk->sk_reuseport; break; case SO_KEEPALIVE: v.val = sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check_tx; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = sk->sk_tsflags; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = sock_flag(sk, SOCK_NOFCS); break; case SO_BINDTODEVICE: return sock_getbindtodevice(sk, optval, optlen, len); case SO_GET_FILTER: len = sk_get_filter(sk, (struct sock_filter __user *)optval, len); if (len < 0) return len; goto lenout; case SO_LOCK_FILTER: v.val = sock_flag(sk, SOCK_FILTER_LOCKED); break; case SO_BPF_EXTENSIONS: v.val = bpf_tell_extensions(); break; case SO_SELECT_ERR_QUEUE: v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: v.val = sk->sk_ll_usec; break; #endif case SO_MAX_PACING_RATE: v.val = sk->sk_max_pacing_rate; break; case SO_INCOMING_CPU: v.val = sk->sk_incoming_cpu; break; default: /* We implement the SO_SNDLOWAT etc to not be settable * (1003.1g 7). */ return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) sk_prot_clear_nulls(sk, prot->obj_size); } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; cgroup_sk_free(&sk->sk_cgrp_data); mem_cgroup_sk_free(sk); security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance * @kern: is this to be a kernel socket? */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sk->sk_net_refcnt = kern ? 0 : 1; if (likely(sk->sk_net_refcnt)) get_net(net); sock_net_set(sk, net); atomic_set(&sk->sk_wmem_alloc, 1); mem_cgroup_sk_alloc(sk); cgroup_sk_alloc(&sk->sk_cgrp_data); sock_update_classid(&sk->sk_cgrp_data); sock_update_netprioidx(&sk->sk_cgrp_data); } return sk; } EXPORT_SYMBOL(sk_alloc); /* Sockets having SOCK_RCU_FREE will call this function after one RCU * grace period. This is the case for UDP sockets and TCP listeners. */ static void __sk_destruct(struct rcu_head *head) { struct sock *sk = container_of(head, struct sock, sk_rcu); struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } if (rcu_access_pointer(sk->sk_reuseport_cb)) reuseport_detach_sock(sk); sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) pr_debug("%s: optmem leakage (%d bytes) detected\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); if (likely(sk->sk_net_refcnt)) put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_destruct(struct sock *sk) { if (sock_flag(sk, SOCK_RCU_FREE)) call_rcu(&sk->sk_rcu, __sk_destruct); else __sk_destruct(&sk->sk_rcu); } static void __sk_free(struct sock *sk) { if (unlikely(sock_diag_has_destroy_listeners(sk) && sk->sk_net_refcnt)) sock_diag_broadcast_destroy(sk); else sk_destruct(sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; bool is_charged = true; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ if (likely(newsk->sk_net_refcnt)) get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; atomic_set(&newsk->sk_drops, 0); newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) /* though it's an empty new sock, the charging may fail * if sysctl_optmem_max was changed between creation of * original socket and cloning */ is_charged = sk_filter_charge(newsk, filter); if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); newsk->sk_err = 0; newsk->sk_err_soft = 0; newsk->sk_priority = 0; newsk->sk_incoming_cpu = raw_smp_processor_id(); atomic64_set(&newsk->sk_cookie, 0); mem_cgroup_sk_alloc(newsk); cgroup_sk_alloc(&newsk->sk_cgrp_data); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { u32 max_segs = 1; sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; max_segs = max_t(u32, dst->dev->gso_max_segs, 1); } } sk->sk_gso_max_segs = max_segs; } EXPORT_SYMBOL_GPL(sk_setup_caps); /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* This variant of sock_wfree() is used by TCP, * since it sets SOCK_USE_WRITE_QUEUE. */ void __sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; if (atomic_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) __sk_free(sk); } void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { skb_orphan(skb); skb->sk = sk; #ifdef CONFIG_INET if (unlikely(!sk_fullsock(sk))) { skb->destructor = sock_edemux; sock_hold(sk); return; } #endif skb->destructor = sock_wfree; skb_set_hash_from_sk(skb, sk); /* * We used to take a refcount on sk, but following operation * is enough to guarantee sk_free() wont free this sock until * all in-flight packets are completed */ atomic_add(skb->truesize, &sk->sk_wmem_alloc); } EXPORT_SYMBOL(skb_set_owner_w); /* This helper is used by netem, as it can hold packets in its * delay queue. We want to allow the owner socket to send more * packets, as if they were already TX completed by a typical driver. * But we also want to keep skb->sk set because some packet schedulers * rely on it (sch_fq for example). So we set skb->truesize to a small * amount (1) and decrease sk_wmem_alloc accordingly. */ void skb_orphan_partial(struct sk_buff *skb) { /* If this skb is a TCP pure ACK or already went here, * we have nothing to do. 2 is already a very small truesize. */ if (skb->truesize <= 2) return; /* TCP stack sets skb->ooo_okay based on sk_wmem_alloc, * so we do not completely orphan skb, but transfert all * accounted bytes but one, to avoid unexpected reorders. */ if (skb->destructor == sock_wfree #ifdef CONFIG_INET || skb->destructor == tcp_wfree #endif ) { atomic_sub(skb->truesize - 1, &skb->sk->sk_wmem_alloc); skb->truesize = 1; } else { skb_orphan(skb); } } EXPORT_SYMBOL(skb_orphan_partial); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); /* * Buffer destructor for skbs that are not used directly in read or write * path, e.g. for error handler skbs. Automatically called from kfree_skb. */ void sock_efree(struct sk_buff *skb) { sock_put(skb->sk); } EXPORT_SYMBOL(sock_efree); kuid_t sock_i_uid(struct sock *sk) { kuid_t uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* Free an option memory block. Note, we actually want the inline * here as this allows gcc to detect the nullify and fold away the * condition entirely. */ static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, const bool nullify) { if (WARN_ON_ONCE(!mem)) return; if (nullify) kzfree(mem); else kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } void sock_kfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, false); } EXPORT_SYMBOL(sock_kfree_s); void sock_kzfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, true); } EXPORT_SYMBOL(sock_kzfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode, int max_page_order) { struct sk_buff *skb; long timeo; int err; timeo = sock_sndtimeo(sk, noblock); for (;;) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf) break; sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb = alloc_skb_with_frags(header_len, data_len, max_page_order, errcode, sk->sk_allocation); if (skb) skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0); } EXPORT_SYMBOL(sock_alloc_send_skb); int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg, struct sockcm_cookie *sockc) { u32 tsflags; switch (cmsg->cmsg_type) { case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; sockc->mark = *(u32 *)CMSG_DATA(cmsg); break; case SO_TIMESTAMPING: if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; tsflags = *(u32 *)CMSG_DATA(cmsg); if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) return -EINVAL; sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; sockc->tsflags |= tsflags; break; /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ case SCM_RIGHTS: case SCM_CREDENTIALS: break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(__sock_cmsg_send); int sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct sockcm_cookie *sockc) { struct cmsghdr *cmsg; int ret; for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; if (cmsg->cmsg_level != SOL_SOCKET) continue; ret = __sock_cmsg_send(sk, msg, cmsg, sockc); if (ret) return ret; } return 0; } EXPORT_SYMBOL(sock_cmsg_send); /* On 32bit arches, an skb frag is limited to 2^15 */ #define SKB_FRAG_PAGE_ORDER get_order(32768) /** * skb_page_frag_refill - check that a page_frag contains enough room * @sz: minimum size of the fragment we want to get * @pfrag: pointer to page_frag * @gfp: priority for memory allocation * * Note: While this allocator tries to use high order pages, there is * no guarantee that allocations succeed. Therefore, @sz MUST be * less or equal than PAGE_SIZE. */ bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) { if (pfrag->page) { if (page_ref_count(pfrag->page) == 1) { pfrag->offset = 0; return true; } if (pfrag->offset + sz <= pfrag->size) return true; put_page(pfrag->page); } pfrag->offset = 0; if (SKB_FRAG_PAGE_ORDER) { /* Avoid direct reclaim but allow kswapd to wake */ pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, SKB_FRAG_PAGE_ORDER); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; return true; } } pfrag->page = alloc_page(gfp); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE; return true; } return false; } EXPORT_SYMBOL(skb_page_frag_refill); bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) { if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) return true; sk_enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); return false; } EXPORT_SYMBOL(sk_page_frag_refill); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb, *next; while ((skb = sk->sk_backlog.head) != NULL) { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; spin_unlock_bh(&sk->sk_lock.slock); do { next = skb->next; prefetch(next); WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); cond_resched(); skb = next; } while (skb != NULL); spin_lock_bh(&sk->sk_lock.slock); } /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } void __sk_flush_backlog(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); __release_sock(sk); spin_unlock_bh(&sk->sk_lock.slock); } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * @skb: last skb seen on sk_receive_queue * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb); sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg && !mem_cgroup_charge_skmem(sk->sk_memcg, amt)) goto suppress_allocation; /* Under limit. */ if (allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. */ if (allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit. */ if (allocated > sk_prot_mem_limits(sk, 2)) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_mem_reclaim - reclaim memory_allocated * @sk: socket * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple) */ void __sk_mem_reclaim(struct sock *sk, int amount) { amount >>= SK_MEM_QUANTUM_SHIFT; sk_memory_allocated_sub(sk, amount); sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT; if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amount); if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); int sk_set_peek_off(struct sock *sk, int val) { if (val < 0) return -EINVAL; sk->sk_peek_off = val; return 0; } EXPORT_SYMBOL_GPL(sk_set_peek_off); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_frag.page = NULL; sk->sk_frag.offset = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); #ifdef CONFIG_NET_RX_BUSY_POLL sk->sk_napi_id = 0; sk->sk_ll_usec = sysctl_net_busy_read; #endif sk->sk_max_pacing_rate = ~0U; sk->sk_pacing_rate = ~0U; sk->sk_incoming_cpu = -1; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); /* Warning : release_cb() might need to release sk ownership, * ie call sock_release_ownership(sk) before us. */ if (sk->sk_prot->release_cb) sk->sk_prot->release_cb(sk); sock_release_ownership(sk); if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (sock_needs_netstamp(sk) && !(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, int level, int type) { struct sock_exterr_skb *serr; struct sk_buff *skb; int copied, err; err = -EAGAIN; skb = sock_dequeue_err_skb(sk); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee); msg->msg_flags |= MSG_ERRQUEUE; err = copied; out_free_skb: kfree_skb(skb); out: return err; } EXPORT_SYMBOL(sock_recv_errqueue); /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); if (sk->sk_frag.page) { put_page(sk->sk_frag.page); sk->sk_frag.page = NULL; } sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { pr_err("PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif static void req_prot_cleanup(struct request_sock_ops *rsk_prot) { if (!rsk_prot) return; kfree(rsk_prot->slab_name); rsk_prot->slab_name = NULL; kmem_cache_destroy(rsk_prot->slab); rsk_prot->slab = NULL; } static int req_prot_init(const struct proto *prot) { struct request_sock_ops *rsk_prot = prot->rsk_prot; if (!rsk_prot) return 0; rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (!rsk_prot->slab_name) return -ENOMEM; rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, rsk_prot->obj_size, 0, prot->slab_flags, NULL); if (!rsk_prot->slab) { pr_crit("%s: Can't create request sock SLAB cache!\n", prot->name); return -ENOMEM; } return 0; } int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { pr_crit("%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (req_prot_init(prot)) goto out_free_request_sock_slab; if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: req_prot_cleanup(prot->rsk_prot); kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); kmem_cache_destroy(prot->slab); prot->slab = NULL; req_prot_cleanup(prot->rsk_prot); if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_create("protocols", S_IRUGO, net->proc_net, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { remove_proc_entry("protocols", net->proc_net); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Generic socket support routines. Memory allocators, socket lock/release * handler for protocols to use and generic option handler. * * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Fixes: * Alan Cox : Numerous verify_area() problems * Alan Cox : Connecting on a connecting socket * now returns an error for tcp. * Alan Cox : sock->protocol is set correctly. * and is not sometimes left as 0. * Alan Cox : connect handles icmp errors on a * connect properly. Unfortunately there * is a restart syscall nasty there. I * can't match BSD without hacking the C * library. Ideas urgently sought! * Alan Cox : Disallow bind() to addresses that are * not ours - especially broadcast ones!! * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost) * Alan Cox : sock_wfree/sock_rfree don't destroy sockets, * instead they leave that for the DESTROY timer. * Alan Cox : Clean up error flag in accept * Alan Cox : TCP ack handling is buggy, the DESTROY timer * was buggy. Put a remove_sock() in the handler * for memory when we hit 0. Also altered the timer * code. The ACK stuff can wait and needs major * TCP layer surgery. * Alan Cox : Fixed TCP ack bug, removed remove sock * and fixed timer/inet_bh race. * Alan Cox : Added zapped flag for TCP * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing. * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so... * Rick Sladkey : Relaxed UDP rules for matching packets. * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support * Pauline Middelink : identd support * Alan Cox : Fixed connect() taking signals I think. * Alan Cox : SO_LINGER supported * Alan Cox : Error reporting fixes * Anonymous : inet_create tidied up (sk->reuse setting) * Alan Cox : inet sockets don't set sk->type! * Alan Cox : Split socket option code * Alan Cox : Callbacks * Alan Cox : Nagle flag for Charles & Johannes stuff * Alex : Removed restriction on inet fioctl * Alan Cox : Splitting INET from NET core * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt() * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code * Alan Cox : Split IP from generic code * Alan Cox : New kfree_skbmem() * Alan Cox : Make SO_DEBUG superuser only. * Alan Cox : Allow anyone to clear SO_DEBUG * (compatibility fix) * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput. * Alan Cox : Allocator for a socket is settable. * Alan Cox : SO_ERROR includes soft errors. * Alan Cox : Allow NULL arguments on some SO_ opts * Alan Cox : Generic socket allocation to make hooks * easier (suggested by Craig Metz). * Michael Pall : SO_ERROR returns positive errno again * Steve Whitehouse: Added default destructor to free * protocol private data. * Steve Whitehouse: Added various other default routines * common to several socket families. * Chris Evans : Call suser() check last on F_SETOWN * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER. * Andi Kleen : Add sock_kmalloc()/sock_kfree_s() * Andi Kleen : Fix write_space callback * Chris Evans : Security fixes - signedness again * Arnaldo C. Melo : cleanups, use skb_queue_purge * * To Fix: * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/capability.h> #include <linux/errno.h> #include <linux/errqueue.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/user_namespace.h> #include <linux/static_key.h> #include <linux/memcontrol.h> #include <linux/prefetch.h> #include <asm/uaccess.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/request_sock.h> #include <net/sock.h> #include <linux/net_tstamp.h> #include <net/xfrm.h> #include <linux/ipsec.h> #include <net/cls_cgroup.h> #include <net/netprio_cgroup.h> #include <linux/sock_diag.h> #include <linux/filter.h> #include <net/sock_reuseport.h> #include <trace/events/sock.h> #ifdef CONFIG_INET #include <net/tcp.h> #endif #include <net/busy_poll.h> static DEFINE_MUTEX(proto_list_mutex); static LIST_HEAD(proto_list); /** * sk_ns_capable - General socket capability test * @sk: Socket to use a capability on or through * @user_ns: The user namespace of the capability to use * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in the user * namespace @user_ns. */ bool sk_ns_capable(const struct sock *sk, struct user_namespace *user_ns, int cap) { return file_ns_capable(sk->sk_socket->file, user_ns, cap) && ns_capable(user_ns, cap); } EXPORT_SYMBOL(sk_ns_capable); /** * sk_capable - Socket global capability test * @sk: Socket to use a capability on or through * @cap: The global capability to use * * Test to see if the opener of the socket had when the socket was * created and the current process has the capability @cap in all user * namespaces. */ bool sk_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, &init_user_ns, cap); } EXPORT_SYMBOL(sk_capable); /** * sk_net_capable - Network namespace socket capability test * @sk: Socket to use a capability on or through * @cap: The capability to use * * Test to see if the opener of the socket had when the socket was created * and the current process has the capability @cap over the network namespace * the socket is a member of. */ bool sk_net_capable(const struct sock *sk, int cap) { return sk_ns_capable(sk, sock_net(sk)->user_ns, cap); } EXPORT_SYMBOL(sk_net_capable); /* * Each address family might have different locking rules, so we have * one slock key per address family: */ static struct lock_class_key af_family_keys[AF_MAX]; static struct lock_class_key af_family_slock_keys[AF_MAX]; /* * Make lock validator output more readable. (we pre-construct these * strings build-time, so that runtime initialization of socket * locks is fast): */ static const char *const af_family_key_strings[AF_MAX+1] = { "sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" , "sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK", "sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" , "sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" , "sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" , "sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" , "sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" , "sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" , "sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" , "sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" , "sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" , "sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" , "sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" , "sk_lock-AF_NFC" , "sk_lock-AF_VSOCK" , "sk_lock-AF_KCM" , "sk_lock-AF_MAX" }; static const char *const af_family_slock_key_strings[AF_MAX+1] = { "slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" , "slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK", "slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" , "slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" , "slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" , "slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" , "slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" , "slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" , "slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" , "slock-27" , "slock-28" , "slock-AF_CAN" , "slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" , "slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" , "slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" , "slock-AF_NFC" , "slock-AF_VSOCK" ,"slock-AF_KCM" , "slock-AF_MAX" }; static const char *const af_family_clock_key_strings[AF_MAX+1] = { "clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" , "clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK", "clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" , "clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" , "clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" , "clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" , "clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" , "clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" , "clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" , "clock-27" , "clock-28" , "clock-AF_CAN" , "clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" , "clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" , "clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" , "clock-AF_NFC" , "clock-AF_VSOCK" , "clock-AF_KCM" , "clock-AF_MAX" }; /* * sk_callback_lock locking rules are per-address-family, * so split the lock classes by using a per-AF key: */ static struct lock_class_key af_callback_keys[AF_MAX]; /* Take into consideration the size of the struct sk_buff overhead in the * determination of these values, since that is non-constant across * platforms. This makes socket queueing behavior and performance * not depend upon such differences. */ #define _SK_MEM_PACKETS 256 #define _SK_MEM_OVERHEAD SKB_TRUESIZE(256) #define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) #define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS) /* Run time adjustable parameters. */ __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX; EXPORT_SYMBOL(sysctl_wmem_max); __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX; EXPORT_SYMBOL(sysctl_rmem_max); __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX; __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX; /* Maximal space eaten by iovec or ancillary data plus some space */ int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512); EXPORT_SYMBOL(sysctl_optmem_max); int sysctl_tstamp_allow_data __read_mostly = 1; struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE; EXPORT_SYMBOL_GPL(memalloc_socks); /** * sk_set_memalloc - sets %SOCK_MEMALLOC * @sk: socket to set it on * * Set %SOCK_MEMALLOC on a socket for access to emergency reserves. * It's the responsibility of the admin to adjust min_free_kbytes * to meet the requirements */ void sk_set_memalloc(struct sock *sk) { sock_set_flag(sk, SOCK_MEMALLOC); sk->sk_allocation |= __GFP_MEMALLOC; static_key_slow_inc(&memalloc_socks); } EXPORT_SYMBOL_GPL(sk_set_memalloc); void sk_clear_memalloc(struct sock *sk) { sock_reset_flag(sk, SOCK_MEMALLOC); sk->sk_allocation &= ~__GFP_MEMALLOC; static_key_slow_dec(&memalloc_socks); /* * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward * progress of swapping. SOCK_MEMALLOC may be cleared while * it has rmem allocations due to the last swapfile being deactivated * but there is a risk that the socket is unusable due to exceeding * the rmem limits. Reclaim the reserves and obey rmem limits again. */ sk_mem_reclaim(sk); } EXPORT_SYMBOL_GPL(sk_clear_memalloc); int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb) { int ret; unsigned long pflags = current->flags; /* these should have been dropped before queueing */ BUG_ON(!sock_flag(sk, SOCK_MEMALLOC)); current->flags |= PF_MEMALLOC; ret = sk->sk_backlog_rcv(sk, skb); tsk_restore_flags(current, pflags, PF_MEMALLOC); return ret; } EXPORT_SYMBOL(__sk_backlog_rcv); static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen) { struct timeval tv; if (optlen < sizeof(tv)) return -EINVAL; if (copy_from_user(&tv, optval, sizeof(tv))) return -EFAULT; if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC) return -EDOM; if (tv.tv_sec < 0) { static int warned __read_mostly; *timeo_p = 0; if (warned < 10 && net_ratelimit()) { warned++; pr_info("%s: `%s' (pid %d) tries to set negative timeout\n", __func__, current->comm, task_pid_nr(current)); } return 0; } *timeo_p = MAX_SCHEDULE_TIMEOUT; if (tv.tv_sec == 0 && tv.tv_usec == 0) return 0; if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1)) *timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ); return 0; } static void sock_warn_obsolete_bsdism(const char *name) { static int warned; static char warncomm[TASK_COMM_LEN]; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n", warncomm, name); warned++; } } static bool sock_needs_netstamp(const struct sock *sk) { switch (sk->sk_family) { case AF_UNSPEC: case AF_UNIX: return false; default: return true; } } static void sock_disable_timestamp(struct sock *sk, unsigned long flags) { if (sk->sk_flags & flags) { sk->sk_flags &= ~flags; if (sock_needs_netstamp(sk) && !(sk->sk_flags & SK_FLAGS_TIMESTAMP)) net_disable_timestamp(); } } int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) { atomic_inc(&sk->sk_drops); trace_sock_rcvqueue_full(sk, skb); return -ENOMEM; } if (!sk_rmem_schedule(sk, skb, skb->truesize)) { atomic_inc(&sk->sk_drops); return -ENOBUFS; } skb->dev = NULL; skb_set_owner_r(skb, sk); /* we escape from rcu protected region, make sure we dont leak * a norefcounted dst */ skb_dst_force(skb); spin_lock_irqsave(&list->lock, flags); sock_skb_set_dropcount(sk, skb); __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; } EXPORT_SYMBOL(__sock_queue_rcv_skb); int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; err = sk_filter(sk, skb); if (err) return err; return __sock_queue_rcv_skb(sk, skb); } EXPORT_SYMBOL(sock_queue_rcv_skb); int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested, unsigned int trim_cap, bool refcounted) { int rc = NET_RX_SUCCESS; if (sk_filter_trim_cap(sk, skb, trim_cap)) goto discard_and_relse; skb->dev = NULL; if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { atomic_inc(&sk->sk_drops); goto discard_and_relse; } if (nested) bh_lock_sock_nested(sk); else bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* * trylock + unlock semantics: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_); rc = sk_backlog_rcv(sk, skb); mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_); } else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); atomic_inc(&sk->sk_drops); goto discard_and_relse; } bh_unlock_sock(sk); out: if (refcounted) sock_put(sk); return rc; discard_and_relse: kfree_skb(skb); goto out; } EXPORT_SYMBOL(__sk_receive_skb); struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_tx_queue_clear(sk); RCU_INIT_POINTER(sk->sk_dst_cache, NULL); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(__sk_dst_check); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } EXPORT_SYMBOL(sk_dst_check); static int sock_setbindtodevice(struct sock *sk, char __user *optval, int optlen) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; int index; /* Sorry... */ ret = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_RAW)) goto out; ret = -EINVAL; if (optlen < 0) goto out; /* Bind this socket to a particular device like "eth0", * as specified in the passed interface name. If the * name is "" or the option length is zero the socket * is not bound. */ if (optlen > IFNAMSIZ - 1) optlen = IFNAMSIZ - 1; memset(devname, 0, sizeof(devname)); ret = -EFAULT; if (copy_from_user(devname, optval, optlen)) goto out; index = 0; if (devname[0] != '\0') { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, devname); if (dev) index = dev->ifindex; rcu_read_unlock(); ret = -ENODEV; if (!dev) goto out; } lock_sock(sk); sk->sk_bound_dev_if = index; sk_dst_reset(sk); release_sock(sk); ret = 0; out: #endif return ret; } static int sock_getbindtodevice(struct sock *sk, char __user *optval, int __user *optlen, int len) { int ret = -ENOPROTOOPT; #ifdef CONFIG_NETDEVICES struct net *net = sock_net(sk); char devname[IFNAMSIZ]; if (sk->sk_bound_dev_if == 0) { len = 0; goto zero; } ret = -EINVAL; if (len < IFNAMSIZ) goto out; ret = netdev_get_name(net, devname, sk->sk_bound_dev_if); if (ret) goto out; len = strlen(devname) + 1; ret = -EFAULT; if (copy_to_user(optval, devname, len)) goto out; zero: ret = -EFAULT; if (put_user(len, optlen)) goto out; ret = 0; out: #endif return ret; } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } bool sk_mc_loop(struct sock *sk) { if (dev_recursion_level()) return false; if (!sk) return true; switch (sk->sk_family) { case AF_INET: return inet_sk(sk)->mc_loop; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: return inet6_sk(sk)->mc_loop; #endif } WARN_ON(1); return true; } EXPORT_SYMBOL(sk_mc_loop); /* * This is meant for all protocols to use and covers goings on * at the socket level. Everything here is generic. */ int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } EXPORT_SYMBOL(sock_setsockopt); static void cred_to_ucred(struct pid *pid, const struct cred *cred, struct ucred *ucred) { ucred->pid = pid_vnr(pid); ucred->uid = ucred->gid = -1; if (cred) { struct user_namespace *current_ns = current_user_ns(); ucred->uid = from_kuid_munged(current_ns, cred->euid); ucred->gid = from_kgid_munged(current_ns, cred->egid); } } int sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; union { int val; struct linger ling; struct timeval tm; } v; int lv = sizeof(int); int len; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; memset(&v, 0, sizeof(v)); switch (optname) { case SO_DEBUG: v.val = sock_flag(sk, SOCK_DBG); break; case SO_DONTROUTE: v.val = sock_flag(sk, SOCK_LOCALROUTE); break; case SO_BROADCAST: v.val = sock_flag(sk, SOCK_BROADCAST); break; case SO_SNDBUF: v.val = sk->sk_sndbuf; break; case SO_RCVBUF: v.val = sk->sk_rcvbuf; break; case SO_REUSEADDR: v.val = sk->sk_reuse; break; case SO_REUSEPORT: v.val = sk->sk_reuseport; break; case SO_KEEPALIVE: v.val = sock_flag(sk, SOCK_KEEPOPEN); break; case SO_TYPE: v.val = sk->sk_type; break; case SO_PROTOCOL: v.val = sk->sk_protocol; break; case SO_DOMAIN: v.val = sk->sk_family; break; case SO_ERROR: v.val = -sock_error(sk); if (v.val == 0) v.val = xchg(&sk->sk_err_soft, 0); break; case SO_OOBINLINE: v.val = sock_flag(sk, SOCK_URGINLINE); break; case SO_NO_CHECK: v.val = sk->sk_no_check_tx; break; case SO_PRIORITY: v.val = sk->sk_priority; break; case SO_LINGER: lv = sizeof(v.ling); v.ling.l_onoff = sock_flag(sk, SOCK_LINGER); v.ling.l_linger = sk->sk_lingertime / HZ; break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("getsockopt"); break; case SO_TIMESTAMP: v.val = sock_flag(sk, SOCK_RCVTSTAMP) && !sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPNS: v.val = sock_flag(sk, SOCK_RCVTSTAMPNS); break; case SO_TIMESTAMPING: v.val = sk->sk_tsflags; break; case SO_RCVTIMEO: lv = sizeof(struct timeval); if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_rcvtimeo / HZ; v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ; } break; case SO_SNDTIMEO: lv = sizeof(struct timeval); if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) { v.tm.tv_sec = 0; v.tm.tv_usec = 0; } else { v.tm.tv_sec = sk->sk_sndtimeo / HZ; v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ; } break; case SO_RCVLOWAT: v.val = sk->sk_rcvlowat; break; case SO_SNDLOWAT: v.val = 1; break; case SO_PASSCRED: v.val = !!test_bit(SOCK_PASSCRED, &sock->flags); break; case SO_PEERCRED: { struct ucred peercred; if (len > sizeof(peercred)) len = sizeof(peercred); cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred); if (copy_to_user(optval, &peercred, len)) return -EFAULT; goto lenout; } case SO_PEERNAME: { char address[128]; if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2)) return -ENOTCONN; if (lv < len) return -EINVAL; if (copy_to_user(optval, address, len)) return -EFAULT; goto lenout; } /* Dubious BSD thing... Probably nobody even uses it, but * the UNIX standard wants it for whatever reason... -DaveM */ case SO_ACCEPTCONN: v.val = sk->sk_state == TCP_LISTEN; break; case SO_PASSSEC: v.val = !!test_bit(SOCK_PASSSEC, &sock->flags); break; case SO_PEERSEC: return security_socket_getpeersec_stream(sock, optval, optlen, len); case SO_MARK: v.val = sk->sk_mark; break; case SO_RXQ_OVFL: v.val = sock_flag(sk, SOCK_RXQ_OVFL); break; case SO_WIFI_STATUS: v.val = sock_flag(sk, SOCK_WIFI_STATUS); break; case SO_PEEK_OFF: if (!sock->ops->set_peek_off) return -EOPNOTSUPP; v.val = sk->sk_peek_off; break; case SO_NOFCS: v.val = sock_flag(sk, SOCK_NOFCS); break; case SO_BINDTODEVICE: return sock_getbindtodevice(sk, optval, optlen, len); case SO_GET_FILTER: len = sk_get_filter(sk, (struct sock_filter __user *)optval, len); if (len < 0) return len; goto lenout; case SO_LOCK_FILTER: v.val = sock_flag(sk, SOCK_FILTER_LOCKED); break; case SO_BPF_EXTENSIONS: v.val = bpf_tell_extensions(); break; case SO_SELECT_ERR_QUEUE: v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: v.val = sk->sk_ll_usec; break; #endif case SO_MAX_PACING_RATE: v.val = sk->sk_max_pacing_rate; break; case SO_INCOMING_CPU: v.val = sk->sk_incoming_cpu; break; default: /* We implement the SO_SNDLOWAT etc to not be settable * (1003.1g 7). */ return -ENOPROTOOPT; } if (len > lv) len = lv; if (copy_to_user(optval, &v, len)) return -EFAULT; lenout: if (put_user(len, optlen)) return -EFAULT; return 0; } /* * Initialize an sk_lock. * * (We also register the sk_lock with the lock validator.) */ static inline void sock_lock_init(struct sock *sk) { sock_lock_init_class_and_name(sk, af_family_slock_key_strings[sk->sk_family], af_family_slock_keys + sk->sk_family, af_family_key_strings[sk->sk_family], af_family_keys + sk->sk_family); } /* * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet, * even temporarly, because of RCU lookups. sk_node should also be left as is. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end */ static void sock_copy(struct sock *nsk, const struct sock *osk) { #ifdef CONFIG_SECURITY_NETWORK void *sptr = nsk->sk_security; #endif memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin)); memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end, osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end)); #ifdef CONFIG_SECURITY_NETWORK nsk->sk_security = sptr; security_sk_clone(osk, nsk); #endif } static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority, int family) { struct sock *sk; struct kmem_cache *slab; slab = prot->slab; if (slab != NULL) { sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO); if (!sk) return sk; if (priority & __GFP_ZERO) sk_prot_clear_nulls(sk, prot->obj_size); } else sk = kmalloc(prot->obj_size, priority); if (sk != NULL) { kmemcheck_annotate_bitfield(sk, flags); if (security_sk_alloc(sk, family, priority)) goto out_free; if (!try_module_get(prot->owner)) goto out_free_sec; sk_tx_queue_clear(sk); } return sk; out_free_sec: security_sk_free(sk); out_free: if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); return NULL; } static void sk_prot_free(struct proto *prot, struct sock *sk) { struct kmem_cache *slab; struct module *owner; owner = prot->owner; slab = prot->slab; cgroup_sk_free(&sk->sk_cgrp_data); mem_cgroup_sk_free(sk); security_sk_free(sk); if (slab != NULL) kmem_cache_free(slab, sk); else kfree(sk); module_put(owner); } /** * sk_alloc - All socket objects are allocated here * @net: the applicable net namespace * @family: protocol family * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * @prot: struct proto associated with this new sock instance * @kern: is this to be a kernel socket? */ struct sock *sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern) { struct sock *sk; sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family); if (sk) { sk->sk_family = family; /* * See comment in struct sock definition to understand * why we need sk_prot_creator -acme */ sk->sk_prot = sk->sk_prot_creator = prot; sock_lock_init(sk); sk->sk_net_refcnt = kern ? 0 : 1; if (likely(sk->sk_net_refcnt)) get_net(net); sock_net_set(sk, net); atomic_set(&sk->sk_wmem_alloc, 1); mem_cgroup_sk_alloc(sk); cgroup_sk_alloc(&sk->sk_cgrp_data); sock_update_classid(&sk->sk_cgrp_data); sock_update_netprioidx(&sk->sk_cgrp_data); } return sk; } EXPORT_SYMBOL(sk_alloc); /* Sockets having SOCK_RCU_FREE will call this function after one RCU * grace period. This is the case for UDP sockets and TCP listeners. */ static void __sk_destruct(struct rcu_head *head) { struct sock *sk = container_of(head, struct sock, sk_rcu); struct sk_filter *filter; if (sk->sk_destruct) sk->sk_destruct(sk); filter = rcu_dereference_check(sk->sk_filter, atomic_read(&sk->sk_wmem_alloc) == 0); if (filter) { sk_filter_uncharge(sk, filter); RCU_INIT_POINTER(sk->sk_filter, NULL); } if (rcu_access_pointer(sk->sk_reuseport_cb)) reuseport_detach_sock(sk); sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP); if (atomic_read(&sk->sk_omem_alloc)) pr_debug("%s: optmem leakage (%d bytes) detected\n", __func__, atomic_read(&sk->sk_omem_alloc)); if (sk->sk_peer_cred) put_cred(sk->sk_peer_cred); put_pid(sk->sk_peer_pid); if (likely(sk->sk_net_refcnt)) put_net(sock_net(sk)); sk_prot_free(sk->sk_prot_creator, sk); } void sk_destruct(struct sock *sk) { if (sock_flag(sk, SOCK_RCU_FREE)) call_rcu(&sk->sk_rcu, __sk_destruct); else __sk_destruct(&sk->sk_rcu); } static void __sk_free(struct sock *sk) { if (unlikely(sock_diag_has_destroy_listeners(sk) && sk->sk_net_refcnt)) sock_diag_broadcast_destroy(sk); else sk_destruct(sk); } void sk_free(struct sock *sk) { /* * We subtract one from sk_wmem_alloc and can know if * some packets are still in some tx queue. * If not null, sock_wfree() will call __sk_free(sk) later */ if (atomic_dec_and_test(&sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sk_free); /** * sk_clone_lock - clone a socket, and lock its clone * @sk: the socket to clone * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority) { struct sock *newsk; bool is_charged = true; newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family); if (newsk != NULL) { struct sk_filter *filter; sock_copy(newsk, sk); /* SANITY */ if (likely(newsk->sk_net_refcnt)) get_net(sock_net(newsk)); sk_node_init(&newsk->sk_node); sock_lock_init(newsk); bh_lock_sock(newsk); newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL; newsk->sk_backlog.len = 0; atomic_set(&newsk->sk_rmem_alloc, 0); /* * sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */ atomic_set(&newsk->sk_wmem_alloc, 1); atomic_set(&newsk->sk_omem_alloc, 0); skb_queue_head_init(&newsk->sk_receive_queue); skb_queue_head_init(&newsk->sk_write_queue); rwlock_init(&newsk->sk_callback_lock); lockdep_set_class_and_name(&newsk->sk_callback_lock, af_callback_keys + newsk->sk_family, af_family_clock_key_strings[newsk->sk_family]); newsk->sk_dst_cache = NULL; newsk->sk_wmem_queued = 0; newsk->sk_forward_alloc = 0; atomic_set(&newsk->sk_drops, 0); newsk->sk_send_head = NULL; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK; sock_reset_flag(newsk, SOCK_DONE); skb_queue_head_init(&newsk->sk_error_queue); filter = rcu_dereference_protected(newsk->sk_filter, 1); if (filter != NULL) /* though it's an empty new sock, the charging may fail * if sysctl_optmem_max was changed between creation of * original socket and cloning */ is_charged = sk_filter_charge(newsk, filter); if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) { /* It is still raw copy of parent, so invalidate * destructor and make plain sk_free() */ newsk->sk_destruct = NULL; bh_unlock_sock(newsk); sk_free(newsk); newsk = NULL; goto out; } RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL); newsk->sk_err = 0; newsk->sk_err_soft = 0; newsk->sk_priority = 0; newsk->sk_incoming_cpu = raw_smp_processor_id(); atomic64_set(&newsk->sk_cookie, 0); mem_cgroup_sk_alloc(newsk); cgroup_sk_alloc(&newsk->sk_cgrp_data); /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&newsk->sk_refcnt, 2); /* * Increment the counter in the same struct proto as the master * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that * is the same as sk->sk_prot->socks, as this field was copied * with memcpy). * * This _changes_ the previous behaviour, where * tcp_create_openreq_child always was incrementing the * equivalent to tcp_prot->socks (inet_sock_nr), so this have * to be taken into account in all callers. -acme */ sk_refcnt_debug_inc(newsk); sk_set_socket(newsk, NULL); newsk->sk_wq = NULL; if (newsk->sk_prot->sockets_allocated) sk_sockets_allocated_inc(newsk); if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); } out: return newsk; } EXPORT_SYMBOL_GPL(sk_clone_lock); void sk_setup_caps(struct sock *sk, struct dst_entry *dst) { u32 max_segs = 1; sk_dst_set(sk, dst); sk->sk_route_caps = dst->dev->features; if (sk->sk_route_caps & NETIF_F_GSO) sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE; sk->sk_route_caps &= ~sk->sk_route_nocaps; if (sk_can_gso(sk)) { if (dst->header_len) { sk->sk_route_caps &= ~NETIF_F_GSO_MASK; } else { sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM; sk->sk_gso_max_size = dst->dev->gso_max_size; max_segs = max_t(u32, dst->dev->gso_max_segs, 1); } } sk->sk_gso_max_segs = max_segs; } EXPORT_SYMBOL_GPL(sk_setup_caps); /* * Simple resource managers for sockets. */ /* * Write buffer destructor automatically called from kfree_skb. */ void sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) { /* * Keep a reference on sk_wmem_alloc, this will be released * after sk_write_space() call */ atomic_sub(len - 1, &sk->sk_wmem_alloc); sk->sk_write_space(sk); len = 1; } /* * if sk_wmem_alloc reaches 0, we must finish what sk_free() * could not do because of in-flight packets */ if (atomic_sub_and_test(len, &sk->sk_wmem_alloc)) __sk_free(sk); } EXPORT_SYMBOL(sock_wfree); /* This variant of sock_wfree() is used by TCP, * since it sets SOCK_USE_WRITE_QUEUE. */ void __sock_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; if (atomic_sub_and_test(skb->truesize, &sk->sk_wmem_alloc)) __sk_free(sk); } void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { skb_orphan(skb); skb->sk = sk; #ifdef CONFIG_INET if (unlikely(!sk_fullsock(sk))) { skb->destructor = sock_edemux; sock_hold(sk); return; } #endif skb->destructor = sock_wfree; skb_set_hash_from_sk(skb, sk); /* * We used to take a refcount on sk, but following operation * is enough to guarantee sk_free() wont free this sock until * all in-flight packets are completed */ atomic_add(skb->truesize, &sk->sk_wmem_alloc); } EXPORT_SYMBOL(skb_set_owner_w); /* This helper is used by netem, as it can hold packets in its * delay queue. We want to allow the owner socket to send more * packets, as if they were already TX completed by a typical driver. * But we also want to keep skb->sk set because some packet schedulers * rely on it (sch_fq for example). So we set skb->truesize to a small * amount (1) and decrease sk_wmem_alloc accordingly. */ void skb_orphan_partial(struct sk_buff *skb) { /* If this skb is a TCP pure ACK or already went here, * we have nothing to do. 2 is already a very small truesize. */ if (skb->truesize <= 2) return; /* TCP stack sets skb->ooo_okay based on sk_wmem_alloc, * so we do not completely orphan skb, but transfert all * accounted bytes but one, to avoid unexpected reorders. */ if (skb->destructor == sock_wfree #ifdef CONFIG_INET || skb->destructor == tcp_wfree #endif ) { atomic_sub(skb->truesize - 1, &skb->sk->sk_wmem_alloc); skb->truesize = 1; } else { skb_orphan(skb); } } EXPORT_SYMBOL(skb_orphan_partial); /* * Read buffer destructor automatically called from kfree_skb. */ void sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; unsigned int len = skb->truesize; atomic_sub(len, &sk->sk_rmem_alloc); sk_mem_uncharge(sk, len); } EXPORT_SYMBOL(sock_rfree); /* * Buffer destructor for skbs that are not used directly in read or write * path, e.g. for error handler skbs. Automatically called from kfree_skb. */ void sock_efree(struct sk_buff *skb) { sock_put(skb->sk); } EXPORT_SYMBOL(sock_efree); kuid_t sock_i_uid(struct sock *sk) { kuid_t uid; read_lock_bh(&sk->sk_callback_lock); uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID; read_unlock_bh(&sk->sk_callback_lock); return uid; } EXPORT_SYMBOL(sock_i_uid); unsigned long sock_i_ino(struct sock *sk) { unsigned long ino; read_lock_bh(&sk->sk_callback_lock); ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0; read_unlock_bh(&sk->sk_callback_lock); return ino; } EXPORT_SYMBOL(sock_i_ino); /* * Allocate a skb from the socket's send buffer. */ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority) { if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { struct sk_buff *skb = alloc_skb(size, priority); if (skb) { skb_set_owner_w(skb, sk); return skb; } } return NULL; } EXPORT_SYMBOL(sock_wmalloc); /* * Allocate a memory block from the socket's option memory buffer. */ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority) { if ((unsigned int)size <= sysctl_optmem_max && atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) { void *mem; /* First do the add, to avoid the race if kmalloc * might sleep. */ atomic_add(size, &sk->sk_omem_alloc); mem = kmalloc(size, priority); if (mem) return mem; atomic_sub(size, &sk->sk_omem_alloc); } return NULL; } EXPORT_SYMBOL(sock_kmalloc); /* Free an option memory block. Note, we actually want the inline * here as this allows gcc to detect the nullify and fold away the * condition entirely. */ static inline void __sock_kfree_s(struct sock *sk, void *mem, int size, const bool nullify) { if (WARN_ON_ONCE(!mem)) return; if (nullify) kzfree(mem); else kfree(mem); atomic_sub(size, &sk->sk_omem_alloc); } void sock_kfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, false); } EXPORT_SYMBOL(sock_kfree_s); void sock_kzfree_s(struct sock *sk, void *mem, int size) { __sock_kfree_s(sk, mem, size, true); } EXPORT_SYMBOL(sock_kzfree_s); /* It is almost wait_for_tcp_memory minus release_sock/lock_sock. I think, these locks should be removed for datagram sockets. */ static long sock_wait_for_wmem(struct sock *sk, long timeo) { DEFINE_WAIT(wait); sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); for (;;) { if (!timeo) break; if (signal_pending(current)) break; set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) break; if (sk->sk_shutdown & SEND_SHUTDOWN) break; if (sk->sk_err) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Generic send/receive buffer handlers */ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode, int max_page_order) { struct sk_buff *skb; long timeo; int err; timeo = sock_sndtimeo(sk, noblock); for (;;) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf) break; sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb = alloc_skb_with_frags(header_len, data_len, max_page_order, errcode, sk->sk_allocation); if (skb) skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } EXPORT_SYMBOL(sock_alloc_send_pskb); struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode) { return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0); } EXPORT_SYMBOL(sock_alloc_send_skb); int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg, struct sockcm_cookie *sockc) { u32 tsflags; switch (cmsg->cmsg_type) { case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; sockc->mark = *(u32 *)CMSG_DATA(cmsg); break; case SO_TIMESTAMPING: if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; tsflags = *(u32 *)CMSG_DATA(cmsg); if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) return -EINVAL; sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; sockc->tsflags |= tsflags; break; /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ case SCM_RIGHTS: case SCM_CREDENTIALS: break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(__sock_cmsg_send); int sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct sockcm_cookie *sockc) { struct cmsghdr *cmsg; int ret; for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; if (cmsg->cmsg_level != SOL_SOCKET) continue; ret = __sock_cmsg_send(sk, msg, cmsg, sockc); if (ret) return ret; } return 0; } EXPORT_SYMBOL(sock_cmsg_send); /* On 32bit arches, an skb frag is limited to 2^15 */ #define SKB_FRAG_PAGE_ORDER get_order(32768) /** * skb_page_frag_refill - check that a page_frag contains enough room * @sz: minimum size of the fragment we want to get * @pfrag: pointer to page_frag * @gfp: priority for memory allocation * * Note: While this allocator tries to use high order pages, there is * no guarantee that allocations succeed. Therefore, @sz MUST be * less or equal than PAGE_SIZE. */ bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp) { if (pfrag->page) { if (page_ref_count(pfrag->page) == 1) { pfrag->offset = 0; return true; } if (pfrag->offset + sz <= pfrag->size) return true; put_page(pfrag->page); } pfrag->offset = 0; if (SKB_FRAG_PAGE_ORDER) { /* Avoid direct reclaim but allow kswapd to wake */ pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) | __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY, SKB_FRAG_PAGE_ORDER); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER; return true; } } pfrag->page = alloc_page(gfp); if (likely(pfrag->page)) { pfrag->size = PAGE_SIZE; return true; } return false; } EXPORT_SYMBOL(skb_page_frag_refill); bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag) { if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation))) return true; sk_enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); return false; } EXPORT_SYMBOL(sk_page_frag_refill); static void __lock_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait, TASK_UNINTERRUPTIBLE); spin_unlock_bh(&sk->sk_lock.slock); schedule(); spin_lock_bh(&sk->sk_lock.slock); if (!sock_owned_by_user(sk)) break; } finish_wait(&sk->sk_lock.wq, &wait); } static void __release_sock(struct sock *sk) __releases(&sk->sk_lock.slock) __acquires(&sk->sk_lock.slock) { struct sk_buff *skb, *next; while ((skb = sk->sk_backlog.head) != NULL) { sk->sk_backlog.head = sk->sk_backlog.tail = NULL; spin_unlock_bh(&sk->sk_lock.slock); do { next = skb->next; prefetch(next); WARN_ON_ONCE(skb_dst_is_noref(skb)); skb->next = NULL; sk_backlog_rcv(sk, skb); cond_resched(); skb = next; } while (skb != NULL); spin_lock_bh(&sk->sk_lock.slock); } /* * Doing the zeroing here guarantee we can not loop forever * while a wild producer attempts to flood us. */ sk->sk_backlog.len = 0; } void __sk_flush_backlog(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); __release_sock(sk); spin_unlock_bh(&sk->sk_lock.slock); } /** * sk_wait_data - wait for data to arrive at sk_receive_queue * @sk: sock to wait on * @timeo: for how long * @skb: last skb seen on sk_receive_queue * * Now socket state including sk->sk_err is changed only under lock, * hence we may omit checks after joining wait queue. * We check receive queue before schedule() only as optimization; * it is very likely that release_sock() added new data. */ int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk); rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb); sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk); finish_wait(sk_sleep(sk), &wait); return rc; } EXPORT_SYMBOL(sk_wait_data); /** * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated * @sk: socket * @size: memory size to allocate * @kind: allocation type * * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means * rmem allocation. This function assumes that protocols which have * memory_pressure use sk_wmem_queued as write buffer accounting. */ int __sk_mem_schedule(struct sock *sk, int size, int kind) { struct proto *prot = sk->sk_prot; int amt = sk_mem_pages(size); long allocated; sk->sk_forward_alloc += amt * SK_MEM_QUANTUM; allocated = sk_memory_allocated_add(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg && !mem_cgroup_charge_skmem(sk->sk_memcg, amt)) goto suppress_allocation; /* Under limit. */ if (allocated <= sk_prot_mem_limits(sk, 0)) { sk_leave_memory_pressure(sk); return 1; } /* Under pressure. */ if (allocated > sk_prot_mem_limits(sk, 1)) sk_enter_memory_pressure(sk); /* Over hard limit. */ if (allocated > sk_prot_mem_limits(sk, 2)) goto suppress_allocation; /* guarantee minimum buffer size under pressure */ if (kind == SK_MEM_RECV) { if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0]) return 1; } else { /* SK_MEM_SEND */ if (sk->sk_type == SOCK_STREAM) { if (sk->sk_wmem_queued < prot->sysctl_wmem[0]) return 1; } else if (atomic_read(&sk->sk_wmem_alloc) < prot->sysctl_wmem[0]) return 1; } if (sk_has_memory_pressure(sk)) { int alloc; if (!sk_under_memory_pressure(sk)) return 1; alloc = sk_sockets_allocated_read_positive(sk); if (sk_prot_mem_limits(sk, 2) > alloc * sk_mem_pages(sk->sk_wmem_queued + atomic_read(&sk->sk_rmem_alloc) + sk->sk_forward_alloc)) return 1; } suppress_allocation: if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) { sk_stream_moderate_sndbuf(sk); /* Fail only if socket is _under_ its sndbuf. * In this case we cannot block, so that we have to fail. */ if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) return 1; } trace_sock_exceed_buf_limit(sk, prot, allocated); /* Alas. Undo changes. */ sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM; sk_memory_allocated_sub(sk, amt); if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amt); return 0; } EXPORT_SYMBOL(__sk_mem_schedule); /** * __sk_mem_reclaim - reclaim memory_allocated * @sk: socket * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple) */ void __sk_mem_reclaim(struct sock *sk, int amount) { amount >>= SK_MEM_QUANTUM_SHIFT; sk_memory_allocated_sub(sk, amount); sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT; if (mem_cgroup_sockets_enabled && sk->sk_memcg) mem_cgroup_uncharge_skmem(sk->sk_memcg, amount); if (sk_under_memory_pressure(sk) && (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0))) sk_leave_memory_pressure(sk); } EXPORT_SYMBOL(__sk_mem_reclaim); int sk_set_peek_off(struct sock *sk, int val) { if (val < 0) return -EINVAL; sk->sk_peek_off = val; return 0; } EXPORT_SYMBOL_GPL(sk_set_peek_off); /* * Set of default routines for initialising struct proto_ops when * the protocol does not support a particular function. In certain * cases where it makes no sense for a protocol to have a "do nothing" * function, some default processing is provided. */ int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_bind); int sock_no_connect(struct socket *sock, struct sockaddr *saddr, int len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_connect); int sock_no_socketpair(struct socket *sock1, struct socket *sock2) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_socketpair); int sock_no_accept(struct socket *sock, struct socket *newsock, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_accept); int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getname); unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt) { return 0; } EXPORT_SYMBOL(sock_no_poll); int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_ioctl); int sock_no_listen(struct socket *sock, int backlog) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_listen); int sock_no_shutdown(struct socket *sock, int how) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_shutdown); int sock_no_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_setsockopt); int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_getsockopt); int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_sendmsg); int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len, int flags) { return -EOPNOTSUPP; } EXPORT_SYMBOL(sock_no_recvmsg); int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma) { /* Mirror missing mmap method error code */ return -ENODEV; } EXPORT_SYMBOL(sock_no_mmap); ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { ssize_t res; struct msghdr msg = {.msg_flags = flags}; struct kvec iov; char *kaddr = kmap(page); iov.iov_base = kaddr + offset; iov.iov_len = size; res = kernel_sendmsg(sock, &msg, &iov, 1, size); kunmap(page); return res; } EXPORT_SYMBOL(sock_no_sendpage); /* * Default Socket Callbacks */ static void sock_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); rcu_read_unlock(); } static void sock_def_error_report(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_poll(&wq->wait, POLLERR); sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); rcu_read_unlock(); } static void sock_def_readable(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } static void sock_def_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); /* Do not wake up a writer until he can make "significant" * progress. --DaveM */ if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) { wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLOUT | POLLWRNORM | POLLWRBAND); /* Should agree with poll, otherwise some programs break */ if (sock_writeable(sk)) sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void sock_def_destruct(struct sock *sk) { } void sk_send_sigurg(struct sock *sk) { if (sk->sk_socket && sk->sk_socket->file) if (send_sigurg(&sk->sk_socket->file->f_owner)) sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI); } EXPORT_SYMBOL(sk_send_sigurg); void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires) { if (!mod_timer(timer, expires)) sock_hold(sk); } EXPORT_SYMBOL(sk_reset_timer); void sk_stop_timer(struct sock *sk, struct timer_list* timer) { if (del_timer(timer)) __sock_put(sk); } EXPORT_SYMBOL(sk_stop_timer); void sock_init_data(struct socket *sock, struct sock *sk) { skb_queue_head_init(&sk->sk_receive_queue); skb_queue_head_init(&sk->sk_write_queue); skb_queue_head_init(&sk->sk_error_queue); sk->sk_send_head = NULL; init_timer(&sk->sk_timer); sk->sk_allocation = GFP_KERNEL; sk->sk_rcvbuf = sysctl_rmem_default; sk->sk_sndbuf = sysctl_wmem_default; sk->sk_state = TCP_CLOSE; sk_set_socket(sk, sock); sock_set_flag(sk, SOCK_ZAPPED); if (sock) { sk->sk_type = sock->type; sk->sk_wq = sock->wq; sock->sk = sk; } else sk->sk_wq = NULL; rwlock_init(&sk->sk_callback_lock); lockdep_set_class_and_name(&sk->sk_callback_lock, af_callback_keys + sk->sk_family, af_family_clock_key_strings[sk->sk_family]); sk->sk_state_change = sock_def_wakeup; sk->sk_data_ready = sock_def_readable; sk->sk_write_space = sock_def_write_space; sk->sk_error_report = sock_def_error_report; sk->sk_destruct = sock_def_destruct; sk->sk_frag.page = NULL; sk->sk_frag.offset = 0; sk->sk_peek_off = -1; sk->sk_peer_pid = NULL; sk->sk_peer_cred = NULL; sk->sk_write_pending = 0; sk->sk_rcvlowat = 1; sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; sk->sk_stamp = ktime_set(-1L, 0); #ifdef CONFIG_NET_RX_BUSY_POLL sk->sk_napi_id = 0; sk->sk_ll_usec = sysctl_net_busy_read; #endif sk->sk_max_pacing_rate = ~0U; sk->sk_pacing_rate = ~0U; sk->sk_incoming_cpu = -1; /* * Before updating sk_refcnt, we must commit prior changes to memory * (Documentation/RCU/rculist_nulls.txt for details) */ smp_wmb(); atomic_set(&sk->sk_refcnt, 1); atomic_set(&sk->sk_drops, 0); } EXPORT_SYMBOL(sock_init_data); void lock_sock_nested(struct sock *sk, int subclass) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_lock.owned) __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_); local_bh_enable(); } EXPORT_SYMBOL(lock_sock_nested); void release_sock(struct sock *sk) { spin_lock_bh(&sk->sk_lock.slock); if (sk->sk_backlog.tail) __release_sock(sk); /* Warning : release_cb() might need to release sk ownership, * ie call sock_release_ownership(sk) before us. */ if (sk->sk_prot->release_cb) sk->sk_prot->release_cb(sk); sock_release_ownership(sk); if (waitqueue_active(&sk->sk_lock.wq)) wake_up(&sk->sk_lock.wq); spin_unlock_bh(&sk->sk_lock.slock); } EXPORT_SYMBOL(release_sock); /** * lock_sock_fast - fast version of lock_sock * @sk: socket * * This version should be used for very small section, where process wont block * return false if fast path is taken * sk_lock.slock locked, owned = 0, BH disabled * return true if slow path is taken * sk_lock.slock unlocked, owned = 1, BH enabled */ bool lock_sock_fast(struct sock *sk) { might_sleep(); spin_lock_bh(&sk->sk_lock.slock); if (!sk->sk_lock.owned) /* * Note : We must disable BH */ return false; __lock_sock(sk); sk->sk_lock.owned = 1; spin_unlock(&sk->sk_lock.slock); /* * The sk_lock has mutex_lock() semantics here: */ mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_); local_bh_enable(); return true; } EXPORT_SYMBOL(lock_sock_fast); int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct timeval tv; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return -ENOENT; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestamp); int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct timespec ts; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return -ENOENT; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0; } EXPORT_SYMBOL(sock_get_timestampns); void sock_enable_timestamp(struct sock *sk, int flag) { if (!sock_flag(sk, flag)) { unsigned long previous_flags = sk->sk_flags; sock_set_flag(sk, flag); /* * we just set one of the two flags which require net * time stamping, but time stamping might have been on * already because of the other one */ if (sock_needs_netstamp(sk) && !(previous_flags & SK_FLAGS_TIMESTAMP)) net_enable_timestamp(); } } int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, int level, int type) { struct sock_exterr_skb *serr; struct sk_buff *skb; int copied, err; err = -EAGAIN; skb = sock_dequeue_err_skb(sk); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_msg(skb, 0, msg, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); serr = SKB_EXT_ERR(skb); put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee); msg->msg_flags |= MSG_ERRQUEUE; err = copied; out_free_skb: kfree_skb(skb); out: return err; } EXPORT_SYMBOL(sock_recv_errqueue); /* * Get a socket option on an socket. * * FIX: POSIX 1003.1g is very ambiguous here. It states that * asynchronous errors should be reported by getsockopt. We assume * this means if you specify SO_ERROR (otherwise whats the point of it). */ int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_getsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_getsockopt != NULL) return sk->sk_prot->compat_getsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_getsockopt); #endif int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int addr_len = 0; int err; err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT, flags & ~MSG_DONTWAIT, &addr_len); if (err >= 0) msg->msg_namelen = addr_len; return err; } EXPORT_SYMBOL(sock_common_recvmsg); /* * Set socket options on an inet socket. */ int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(sock_common_setsockopt); #ifdef CONFIG_COMPAT int compat_sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; if (sk->sk_prot->compat_setsockopt != NULL) return sk->sk_prot->compat_setsockopt(sk, level, optname, optval, optlen); return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_sock_common_setsockopt); #endif void sk_common_release(struct sock *sk) { if (sk->sk_prot->destroy) sk->sk_prot->destroy(sk); /* * Observation: when sock_common_release is called, processes have * no access to socket. But net still has. * Step one, detach it from networking: * * A. Remove from hash tables. */ sk->sk_prot->unhash(sk); /* * In this point socket cannot receive new packets, but it is possible * that some packets are in flight because some CPU runs receiver and * did hash table lookup before we unhashed socket. They will achieve * receive queue and will be purged by socket destructor. * * Also we still have packets pending on receive queue and probably, * our own packets waiting in device queues. sock_destroy will drain * receive queue, but transmitted packets will delay socket destruction * until the last reference will be released. */ sock_orphan(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); if (sk->sk_frag.page) { put_page(sk->sk_frag.page); sk->sk_frag.page = NULL; } sock_put(sk); } EXPORT_SYMBOL(sk_common_release); #ifdef CONFIG_PROC_FS #define PROTO_INUSE_NR 64 /* should be enough for the first time */ struct prot_inuse { int val[PROTO_INUSE_NR]; }; static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR); #ifdef CONFIG_NET_NS void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(net->core.inuse->val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu_ptr(net->core.inuse, cpu)->val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); static int __net_init sock_inuse_init_net(struct net *net) { net->core.inuse = alloc_percpu(struct prot_inuse); return net->core.inuse ? 0 : -ENOMEM; } static void __net_exit sock_inuse_exit_net(struct net *net) { free_percpu(net->core.inuse); } static struct pernet_operations net_inuse_ops = { .init = sock_inuse_init_net, .exit = sock_inuse_exit_net, }; static __init int net_inuse_init(void) { if (register_pernet_subsys(&net_inuse_ops)) panic("Cannot initialize net inuse counters"); return 0; } core_initcall(net_inuse_init); #else static DEFINE_PER_CPU(struct prot_inuse, prot_inuse); void sock_prot_inuse_add(struct net *net, struct proto *prot, int val) { __this_cpu_add(prot_inuse.val[prot->inuse_idx], val); } EXPORT_SYMBOL_GPL(sock_prot_inuse_add); int sock_prot_inuse_get(struct net *net, struct proto *prot) { int cpu, idx = prot->inuse_idx; int res = 0; for_each_possible_cpu(cpu) res += per_cpu(prot_inuse, cpu).val[idx]; return res >= 0 ? res : 0; } EXPORT_SYMBOL_GPL(sock_prot_inuse_get); #endif static void assign_proto_idx(struct proto *prot) { prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR); if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) { pr_err("PROTO_INUSE_NR exhausted\n"); return; } set_bit(prot->inuse_idx, proto_inuse_idx); } static void release_proto_idx(struct proto *prot) { if (prot->inuse_idx != PROTO_INUSE_NR - 1) clear_bit(prot->inuse_idx, proto_inuse_idx); } #else static inline void assign_proto_idx(struct proto *prot) { } static inline void release_proto_idx(struct proto *prot) { } #endif static void req_prot_cleanup(struct request_sock_ops *rsk_prot) { if (!rsk_prot) return; kfree(rsk_prot->slab_name); rsk_prot->slab_name = NULL; kmem_cache_destroy(rsk_prot->slab); rsk_prot->slab = NULL; } static int req_prot_init(const struct proto *prot) { struct request_sock_ops *rsk_prot = prot->rsk_prot; if (!rsk_prot) return 0; rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name); if (!rsk_prot->slab_name) return -ENOMEM; rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name, rsk_prot->obj_size, 0, prot->slab_flags, NULL); if (!rsk_prot->slab) { pr_crit("%s: Can't create request sock SLAB cache!\n", prot->name); return -ENOMEM; } return 0; } int proto_register(struct proto *prot, int alloc_slab) { if (alloc_slab) { prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0, SLAB_HWCACHE_ALIGN | prot->slab_flags, NULL); if (prot->slab == NULL) { pr_crit("%s: Can't create sock SLAB cache!\n", prot->name); goto out; } if (req_prot_init(prot)) goto out_free_request_sock_slab; if (prot->twsk_prot != NULL) { prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name); if (prot->twsk_prot->twsk_slab_name == NULL) goto out_free_request_sock_slab; prot->twsk_prot->twsk_slab = kmem_cache_create(prot->twsk_prot->twsk_slab_name, prot->twsk_prot->twsk_obj_size, 0, prot->slab_flags, NULL); if (prot->twsk_prot->twsk_slab == NULL) goto out_free_timewait_sock_slab_name; } } mutex_lock(&proto_list_mutex); list_add(&prot->node, &proto_list); assign_proto_idx(prot); mutex_unlock(&proto_list_mutex); return 0; out_free_timewait_sock_slab_name: kfree(prot->twsk_prot->twsk_slab_name); out_free_request_sock_slab: req_prot_cleanup(prot->rsk_prot); kmem_cache_destroy(prot->slab); prot->slab = NULL; out: return -ENOBUFS; } EXPORT_SYMBOL(proto_register); void proto_unregister(struct proto *prot) { mutex_lock(&proto_list_mutex); release_proto_idx(prot); list_del(&prot->node); mutex_unlock(&proto_list_mutex); kmem_cache_destroy(prot->slab); prot->slab = NULL; req_prot_cleanup(prot->rsk_prot); if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) { kmem_cache_destroy(prot->twsk_prot->twsk_slab); kfree(prot->twsk_prot->twsk_slab_name); prot->twsk_prot->twsk_slab = NULL; } } EXPORT_SYMBOL(proto_unregister); #ifdef CONFIG_PROC_FS static void *proto_seq_start(struct seq_file *seq, loff_t *pos) __acquires(proto_list_mutex) { mutex_lock(&proto_list_mutex); return seq_list_start_head(&proto_list, *pos); } static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &proto_list, pos); } static void proto_seq_stop(struct seq_file *seq, void *v) __releases(proto_list_mutex) { mutex_unlock(&proto_list_mutex); } static char proto_method_implemented(const void *method) { return method == NULL ? 'n' : 'y'; } static long sock_prot_memory_allocated(struct proto *proto) { return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L; } static char *sock_prot_memory_pressure(struct proto *proto) { return proto->memory_pressure != NULL ? proto_memory_pressure(proto) ? "yes" : "no" : "NI"; } static void proto_seq_printf(struct seq_file *seq, struct proto *proto) { seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s " "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n", proto->name, proto->obj_size, sock_prot_inuse_get(seq_file_net(seq), proto), sock_prot_memory_allocated(proto), sock_prot_memory_pressure(proto), proto->max_header, proto->slab == NULL ? "no" : "yes", module_name(proto->owner), proto_method_implemented(proto->close), proto_method_implemented(proto->connect), proto_method_implemented(proto->disconnect), proto_method_implemented(proto->accept), proto_method_implemented(proto->ioctl), proto_method_implemented(proto->init), proto_method_implemented(proto->destroy), proto_method_implemented(proto->shutdown), proto_method_implemented(proto->setsockopt), proto_method_implemented(proto->getsockopt), proto_method_implemented(proto->sendmsg), proto_method_implemented(proto->recvmsg), proto_method_implemented(proto->sendpage), proto_method_implemented(proto->bind), proto_method_implemented(proto->backlog_rcv), proto_method_implemented(proto->hash), proto_method_implemented(proto->unhash), proto_method_implemented(proto->get_port), proto_method_implemented(proto->enter_memory_pressure)); } static int proto_seq_show(struct seq_file *seq, void *v) { if (v == &proto_list) seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s", "protocol", "size", "sockets", "memory", "press", "maxhdr", "slab", "module", "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n"); else proto_seq_printf(seq, list_entry(v, struct proto, node)); return 0; } static const struct seq_operations proto_seq_ops = { .start = proto_seq_start, .next = proto_seq_next, .stop = proto_seq_stop, .show = proto_seq_show, }; static int proto_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &proto_seq_ops, sizeof(struct seq_net_private)); } static const struct file_operations proto_seq_fops = { .owner = THIS_MODULE, .open = proto_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static __net_init int proto_init_net(struct net *net) { if (!proc_create("protocols", S_IRUGO, net->proc_net, &proto_seq_fops)) return -ENOMEM; return 0; } static __net_exit void proto_exit_net(struct net *net) { remove_proc_entry("protocols", net->proc_net); } static __net_initdata struct pernet_operations proto_net_ops = { .init = proto_init_net, .exit = proto_exit_net, }; static int __init proto_init(void) { return register_pernet_subsys(&proto_net_ops); } subsys_initcall(proto_init); #endif /* PROC_FS */
int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }
int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }
{'added': [(718, '\t\tsk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);'), (754, '\t\tsk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);')], 'deleted': [(718, '\t\tsk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF);'), (754, '\t\tsk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF);')]}
2
2
2,139
12,440
https://github.com/torvalds/linux
CVE-2016-9793
['CWE-119']
wddx.c
php_wddx_process_data
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { char *escaped; size_t escaped_len; TSRMLS_FETCH(); escaped = php_escape_html_entities( comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, escaped, escaped_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); str_efree(escaped); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); str_efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); str_efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i], strlen(atts[i])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) { zval *tmp; char *key; char *p1, *p2, *endp; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { char *escaped; size_t escaped_len; TSRMLS_FETCH(); escaped = php_escape_html_entities( comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, escaped, escaped_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); str_efree(escaped); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); str_efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); str_efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i], strlen(atts[i])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) { zval *tmp; char *key; char *p1, *p2, *endp; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
*/ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } }
*/ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } }
{'added': [(1126, '\t\t\t\tif (Z_TYPE_P(ent->data) == IS_STRING) {'), (1127, '\t\t\t\t\ttmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1);'), (1128, '\t\t\t\t\tmemcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data));'), (1129, '\t\t\t\t\tmemcpy(tmp + Z_STRLEN_P(ent->data), s, len);'), (1130, '\t\t\t\t\tlen += Z_STRLEN_P(ent->data);'), (1131, '\t\t\t\t\tefree(Z_STRVAL_P(ent->data));'), (1132, '\t\t\t\t\tZ_TYPE_P(ent->data) = IS_LONG;'), (1133, '\t\t\t\t} else {'), (1134, '\t\t\t\t\ttmp = emalloc(len + 1);'), (1135, '\t\t\t\t\tmemcpy(tmp, s, len);'), (1136, '\t\t\t\t}'), (1142, '\t\t\t\t\tZVAL_STRINGL(ent->data, tmp, len, 0);'), (1143, '\t\t\t\t} else {'), (1144, '\t\t\t\t\tefree(tmp);')], 'deleted': [(1126, '\t\t\t\ttmp = emalloc(len + 1);'), (1127, '\t\t\t\tmemcpy(tmp, s, len);'), (1133, '\t\t\t\t\tZ_TYPE_P(ent->data) = IS_STRING;'), (1134, '\t\t\t\t\tZ_STRLEN_P(ent->data) = len;'), (1135, '\t\t\t\t\tZ_STRVAL_P(ent->data) = estrndup(s, len);'), (1137, '\t\t\t\tefree(tmp);')]}
14
6
980
6,665
https://github.com/php/php-src
CVE-2016-7129
['CWE-20']
algif_hash.c
hash_accept
/* * algif_hash: User-space interface for hash algorithms * * This file provides the user-space API for hash algorithms. * * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/hash.h> #include <crypto/if_alg.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/net.h> #include <net/sock.h> struct hash_ctx { struct af_alg_sgl sgl; u8 *result; struct af_alg_completion completion; unsigned int len; bool more; struct ahash_request req; }; static int hash_sendmsg(struct socket *sock, struct msghdr *msg, size_t ignored) { int limit = ALG_MAX_PAGES * PAGE_SIZE; struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; long copied = 0; int err; if (limit > sk->sk_sndbuf) limit = sk->sk_sndbuf; lock_sock(sk); if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } ctx->more = 0; while (msg_data_left(msg)) { int len = msg_data_left(msg); if (len > limit) len = limit; len = af_alg_make_sg(&ctx->sgl, &msg->msg_iter, len); if (len < 0) { err = copied ? 0 : len; goto unlock; } ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, len); err = af_alg_wait_for_completion(crypto_ahash_update(&ctx->req), &ctx->completion); af_alg_free_sg(&ctx->sgl); if (err) goto unlock; copied += len; iov_iter_advance(&msg->msg_iter, len); } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more) { ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); } unlock: release_sock(sk); return err ?: copied; } static ssize_t hash_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; int err; if (flags & MSG_SENDPAGE_NOTLAST) flags |= MSG_MORE; lock_sock(sk); sg_init_table(ctx->sgl.sg, 1); sg_set_page(ctx->sgl.sg, page, size, offset); ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size); if (!(flags & MSG_MORE)) { if (ctx->more) err = crypto_ahash_finup(&ctx->req); else err = crypto_ahash_digest(&ctx->req); } else { if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } err = crypto_ahash_update(&ctx->req); } err = af_alg_wait_for_completion(err, &ctx->completion); if (err) goto unlock; ctx->more = flags & MSG_MORE; unlock: release_sock(sk); return err ?: size; } static int hash_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_to_msg(msg, ctx->result, len); unlock: release_sock(sk); return err ?: len; } static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } static struct proto_ops algif_hash_ops = { .family = PF_ALG, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .bind = sock_no_bind, .setsockopt = sock_no_setsockopt, .poll = sock_no_poll, .release = af_alg_release, .sendmsg = hash_sendmsg, .sendpage = hash_sendpage, .recvmsg = hash_recvmsg, .accept = hash_accept, }; static void *hash_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_ahash(name, type, mask); } static void hash_release(void *private) { crypto_free_ahash(private); } static int hash_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ahash_setkey(private, key, keylen); } static void hash_sock_destruct(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; sock_kzfree_s(sk, ctx->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req))); sock_kfree_s(sk, ctx, ctx->len); af_alg_release_parent(sk); } static int hash_accept_parent(void *private, struct sock *sk) { struct hash_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private); unsigned ds = crypto_ahash_digestsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL); if (!ctx->result) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->result, 0, ds); ctx->len = len; ctx->more = 0; af_alg_init_completion(&ctx->completion); ask->private = ctx; ahash_request_set_tfm(&ctx->req, private); ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = hash_sock_destruct; return 0; } static const struct af_alg_type algif_type_hash = { .bind = hash_bind, .release = hash_release, .setkey = hash_setkey, .accept = hash_accept_parent, .ops = &algif_hash_ops, .name = "hash", .owner = THIS_MODULE }; static int __init algif_hash_init(void) { return af_alg_register_type(&algif_type_hash); } static void __exit algif_hash_exit(void) { int err = af_alg_unregister_type(&algif_type_hash); BUG_ON(err); } module_init(algif_hash_init); module_exit(algif_hash_exit); MODULE_LICENSE("GPL");
/* * algif_hash: User-space interface for hash algorithms * * This file provides the user-space API for hash algorithms. * * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/hash.h> #include <crypto/if_alg.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/net.h> #include <net/sock.h> struct hash_ctx { struct af_alg_sgl sgl; u8 *result; struct af_alg_completion completion; unsigned int len; bool more; struct ahash_request req; }; static int hash_sendmsg(struct socket *sock, struct msghdr *msg, size_t ignored) { int limit = ALG_MAX_PAGES * PAGE_SIZE; struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; long copied = 0; int err; if (limit > sk->sk_sndbuf) limit = sk->sk_sndbuf; lock_sock(sk); if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } ctx->more = 0; while (msg_data_left(msg)) { int len = msg_data_left(msg); if (len > limit) len = limit; len = af_alg_make_sg(&ctx->sgl, &msg->msg_iter, len); if (len < 0) { err = copied ? 0 : len; goto unlock; } ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, len); err = af_alg_wait_for_completion(crypto_ahash_update(&ctx->req), &ctx->completion); af_alg_free_sg(&ctx->sgl); if (err) goto unlock; copied += len; iov_iter_advance(&msg->msg_iter, len); } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more) { ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); } unlock: release_sock(sk); return err ?: copied; } static ssize_t hash_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; int err; if (flags & MSG_SENDPAGE_NOTLAST) flags |= MSG_MORE; lock_sock(sk); sg_init_table(ctx->sgl.sg, 1); sg_set_page(ctx->sgl.sg, page, size, offset); ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size); if (!(flags & MSG_MORE)) { if (ctx->more) err = crypto_ahash_finup(&ctx->req); else err = crypto_ahash_digest(&ctx->req); } else { if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } err = crypto_ahash_update(&ctx->req); } err = af_alg_wait_for_completion(err, &ctx->completion); if (err) goto unlock; ctx->more = flags & MSG_MORE; unlock: release_sock(sk); return err ?: size; } static int hash_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_to_msg(msg, ctx->result, len); unlock: release_sock(sk); return err ?: len; } static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; bool more; int err; lock_sock(sk); more = ctx->more; err = more ? crypto_ahash_export(req, state) : 0; release_sock(sk); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = more; if (!more) return err; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } static struct proto_ops algif_hash_ops = { .family = PF_ALG, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .bind = sock_no_bind, .setsockopt = sock_no_setsockopt, .poll = sock_no_poll, .release = af_alg_release, .sendmsg = hash_sendmsg, .sendpage = hash_sendpage, .recvmsg = hash_recvmsg, .accept = hash_accept, }; static void *hash_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_ahash(name, type, mask); } static void hash_release(void *private) { crypto_free_ahash(private); } static int hash_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ahash_setkey(private, key, keylen); } static void hash_sock_destruct(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; sock_kzfree_s(sk, ctx->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req))); sock_kfree_s(sk, ctx, ctx->len); af_alg_release_parent(sk); } static int hash_accept_parent(void *private, struct sock *sk) { struct hash_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private); unsigned ds = crypto_ahash_digestsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL); if (!ctx->result) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->result, 0, ds); ctx->len = len; ctx->more = 0; af_alg_init_completion(&ctx->completion); ask->private = ctx; ahash_request_set_tfm(&ctx->req, private); ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = hash_sock_destruct; return 0; } static const struct af_alg_type algif_type_hash = { .bind = hash_bind, .release = hash_release, .setkey = hash_setkey, .accept = hash_accept_parent, .ops = &algif_hash_ops, .name = "hash", .owner = THIS_MODULE }; static int __init algif_hash_init(void) { return af_alg_register_type(&algif_type_hash); } static void __exit algif_hash_exit(void) { int err = af_alg_unregister_type(&algif_type_hash); BUG_ON(err); } module_init(algif_hash_init); module_exit(algif_hash_exit); MODULE_LICENSE("GPL");
static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; }
static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; bool more; int err; lock_sock(sk); more = ctx->more; err = more ? crypto_ahash_export(req, state) : 0; release_sock(sk); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = more; if (!more) return err; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; }
{'added': [(184, '\tbool more;'), (187, '\tlock_sock(sk);'), (188, '\tmore = ctx->more;'), (189, '\terr = more ? crypto_ahash_export(req, state) : 0;'), (190, '\trelease_sock(sk);'), (191, ''), (202, '\tctx2->more = more;'), (203, ''), (204, '\tif (!more)'), (205, '\t\treturn err;')], 'deleted': [(186, '\terr = crypto_ahash_export(req, state);'), (197, '\tctx2->more = 1;')]}
10
2
243
1,482
https://github.com/torvalds/linux
CVE-2016-8646
['CWE-476']
snmp-engine.c
snmp_engine
/* * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * An implementation of the Simple Network Management Protocol (RFC 3411-3418) * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-oid.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length) { snmp_mib_resource_t *resource; uint32_t i, j, original_varbinds_length; uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN]; uint8_t repeater; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = *varbinds_length; for(i = 0; i < original_varbinds_length; i++) { snmp_oid_copy(oid[i], varbinds[i].oid); } *varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->error_status_non_repeaters.non_repeaters) { break; } resource = snmp_mib_find_next(oid[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; } } } for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) { repeater = 0; for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(oid[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = *varbinds_length + 1; break; case SNMP_VERSION_2C: if(*varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]); (*varbinds_length)++; } break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; snmp_oid_copy(oid[j], resource->oid); repeater++; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ unsigned char * snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len) { static snmp_header_t header; static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; static uint32_t varbind_length = SNMP_MAX_NR_VALUES; buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length); if(buff == NULL) { return NULL; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return NULL; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case SNMP_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) { return NULL; } break; default: LOG_ERR("Invalid request type"); return NULL; } header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE; out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length); return ++out; }
/* * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * SNMP Implementation of the protocol engine * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-ber.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; snmp_oid_t oids[SNMP_MAX_NR_VALUES]; uint32_t j, original_varbinds_length; uint8_t repeater; uint8_t i, varbinds_length; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = 0; while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) { memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t)); original_varbinds_length++; } varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->non_repeaters) { break; } resource = snmp_mib_find_next(&oids[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; } else { return -1; } } } for(i = 0; i < header->max_repetitions; i++) { repeater = 0; for(j = header->non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(&oids[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = varbinds_length + 1; break; case SNMP_VERSION_2C: if(varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t)); (varbinds_length)++; } else { return -1; } break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t)); repeater++; } else { return -1; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine(snmp_packet_t *snmp_packet) { snmp_header_t header; snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; memset(&header, 0, sizeof(header)); memset(varbinds, 0, sizeof(varbinds)); if(!snmp_message_decode(snmp_packet, &header, varbinds)) { return 0; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return 0; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case BER_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds) == -1) { return 0; } break; default: LOG_ERR("Invalid request type"); return 0; } header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE; return snmp_message_encode(snmp_packet, &header, varbinds); }
snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len) { static snmp_header_t header; static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; static uint32_t varbind_length = SNMP_MAX_NR_VALUES; buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length); if(buff == NULL) { return NULL; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return NULL; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case SNMP_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) { return NULL; } break; default: LOG_ERR("Invalid request type"); return NULL; } header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE; out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length); return ++out; }
snmp_engine(snmp_packet_t *snmp_packet) { snmp_header_t header; snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; memset(&header, 0, sizeof(header)); memset(varbinds, 0, sizeof(varbinds)); if(!snmp_message_decode(snmp_packet, &header, varbinds)) { return 0; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return 0; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case BER_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds) == -1) { return 0; } break; default: LOG_ERR("Invalid request type"); return 0; } header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE; return snmp_message_encode(snmp_packet, &header, varbinds); }
{'added': [(2, ' * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * SNMP Implementation of the protocol engine'), (45, '#include "snmp-ber.h"'), (51, 'static inline int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds)'), (55, ' uint8_t i;'), (57, ' i = 0;'), (58, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (59, ' resource = snmp_mib_find(&varbinds[i].oid);'), (63, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (67, ' header->error_index = i + 1;'), (70, ' (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;'), (73, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (74, ' header->error_index = 0;'), (77, ' resource->handler(&varbinds[i], &resource->oid);'), (79, ''), (80, ' i++;'), (86, 'static inline int'), (87, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)'), (90, ' uint8_t i;'), (92, ' i = 0;'), (93, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (94, ' resource = snmp_mib_find_next(&varbinds[i].oid);'), (98, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (102, ' header->error_index = i + 1;'), (105, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (108, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (109, ' header->error_index = 0;'), (112, ' resource->handler(&varbinds[i], &resource->oid);'), (114, ''), (115, ' i++;'), (121, 'static inline int'), (122, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)'), (125, ' snmp_oid_t oids[SNMP_MAX_NR_VALUES];'), (126, ' uint32_t j, original_varbinds_length;'), (128, ' uint8_t i, varbinds_length;'), (134, ' original_varbinds_length = 0;'), (135, ' while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {'), (136, ' memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));'), (137, ' original_varbinds_length++;'), (140, ' varbinds_length = 0;'), (142, ' if(i >= header->non_repeaters) {'), (146, ' resource = snmp_mib_find_next(&oids[i]);'), (150, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (154, ' header->error_index = i + 1;'), (157, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (160, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (161, ' header->error_index = 0;'), (164, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (165, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (166, ' (varbinds_length)++;'), (167, ' } else {'), (168, ' return -1;'), (173, ' for(i = 0; i < header->max_repetitions; i++) {'), (175, ' for(j = header->non_repeaters; j < original_varbinds_length; j++) {'), (176, ' resource = snmp_mib_find_next(&oids[j]);'), (180, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (184, ' header->error_index = varbinds_length + 1;'), (187, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (188, ' (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (189, ' memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));'), (190, ' (varbinds_length)++;'), (191, ' } else {'), (192, ' return -1;'), (196, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (197, ' header->error_index = 0;'), (200, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (201, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (202, ' (varbinds_length)++;'), (203, ' memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));'), (205, ' } else {'), (206, ' return -1;'), (218, 'int'), (219, 'snmp_engine(snmp_packet_t *snmp_packet)'), (221, ' snmp_header_t header;'), (222, ' snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (223, ''), (224, ' memset(&header, 0, sizeof(header));'), (225, ' memset(varbinds, 0, sizeof(varbinds));'), (227, ' if(!snmp_message_decode(snmp_packet, &header, varbinds)) {'), (228, ' return 0;'), (234, ' return 0;'), (242, ' case BER_DATA_TYPE_PDU_GET_REQUEST:'), (243, ' if(snmp_engine_get(&header, varbinds) == -1) {'), (244, ' return 0;'), (248, ' case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (249, ' if(snmp_engine_get_next(&header, varbinds) == -1) {'), (250, ' return 0;'), (254, ' case BER_DATA_TYPE_PDU_GET_BULK:'), (255, ' if(snmp_engine_get_bulk(&header, varbinds) == -1) {'), (256, ' return 0;'), (262, ' return 0;'), (265, ' header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;'), (267, ' return snmp_message_encode(snmp_packet, &header, varbinds);')], 'deleted': [(2, ' * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * An implementation of the Simple Network Management Protocol (RFC 3411-3418)'), (45, '#include "snmp-oid.h"'), (51, 'int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (55, ' uint32_t i;'), (57, ' for(i = 0; i < varbinds_length; i++) {'), (58, ' resource = snmp_mib_find(varbinds[i].oid);'), (62, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (66, ' header->error_index_max_repetitions.error_index = i + 1;'), (69, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;'), (72, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (73, ' header->error_index_max_repetitions.error_index = 0;'), (76, ' resource->handler(&varbinds[i], resource->oid);'), (83, 'int'), (84, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (87, ' uint32_t i;'), (89, ' for(i = 0; i < varbinds_length; i++) {'), (90, ' resource = snmp_mib_find_next(varbinds[i].oid);'), (94, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (98, ' header->error_index_max_repetitions.error_index = i + 1;'), (101, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (104, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (105, ' header->error_index_max_repetitions.error_index = 0;'), (108, ' resource->handler(&varbinds[i], resource->oid);'), (115, 'int'), (116, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)'), (119, ' uint32_t i, j, original_varbinds_length;'), (120, ' uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];'), (127, ' original_varbinds_length = *varbinds_length;'), (128, ' for(i = 0; i < original_varbinds_length; i++) {'), (129, ' snmp_oid_copy(oid[i], varbinds[i].oid);'), (132, ' *varbinds_length = 0;'), (134, ' if(i >= header->error_status_non_repeaters.non_repeaters) {'), (138, ' resource = snmp_mib_find_next(oid[i]);'), (142, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (146, ' header->error_index_max_repetitions.error_index = i + 1;'), (149, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (152, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (153, ' header->error_index_max_repetitions.error_index = 0;'), (156, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (157, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (158, ' (*varbinds_length)++;'), (163, ' for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {'), (165, ' for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {'), (166, ' resource = snmp_mib_find_next(oid[j]);'), (170, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (174, ' header->error_index_max_repetitions.error_index = *varbinds_length + 1;'), (177, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (178, ' (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (179, ' snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);'), (180, ' (*varbinds_length)++;'), (184, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (185, ' header->error_index_max_repetitions.error_index = 0;'), (188, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (189, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (190, ' (*varbinds_length)++;'), (191, ' snmp_oid_copy(oid[j], resource->oid);'), (204, 'unsigned char *'), (205, 'snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)'), (207, ' static snmp_header_t header;'), (208, ' static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (209, ' static uint32_t varbind_length = SNMP_MAX_NR_VALUES;'), (211, ' buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);'), (212, ' if(buff == NULL) {'), (213, ' return NULL;'), (219, ' return NULL;'), (227, ' case SNMP_DATA_TYPE_PDU_GET_REQUEST:'), (228, ' if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {'), (229, ' return NULL;'), (233, ' case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (234, ' if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {'), (235, ' return NULL;'), (239, ' case SNMP_DATA_TYPE_PDU_GET_BULK:'), (240, ' if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {'), (241, ' return NULL;'), (247, ' return NULL;'), (250, ' header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;'), (251, ' out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);'), (253, ' return ++out;')]}
94
80
181
966
https://github.com/contiki-ng/contiki-ng
CVE-2020-12141
['CWE-125']
snmp-engine.c
snmp_engine_get
/* * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * An implementation of the Simple Network Management Protocol (RFC 3411-3418) * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-oid.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length) { snmp_mib_resource_t *resource; uint32_t i, j, original_varbinds_length; uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN]; uint8_t repeater; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = *varbinds_length; for(i = 0; i < original_varbinds_length; i++) { snmp_oid_copy(oid[i], varbinds[i].oid); } *varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->error_status_non_repeaters.non_repeaters) { break; } resource = snmp_mib_find_next(oid[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; } } } for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) { repeater = 0; for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(oid[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = *varbinds_length + 1; break; case SNMP_VERSION_2C: if(*varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]); (*varbinds_length)++; } break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; snmp_oid_copy(oid[j], resource->oid); repeater++; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ unsigned char * snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len) { static snmp_header_t header; static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; static uint32_t varbind_length = SNMP_MAX_NR_VALUES; buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length); if(buff == NULL) { return NULL; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return NULL; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case SNMP_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) { return NULL; } break; default: LOG_ERR("Invalid request type"); return NULL; } header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE; out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length); return ++out; }
/* * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * SNMP Implementation of the protocol engine * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-ber.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; snmp_oid_t oids[SNMP_MAX_NR_VALUES]; uint32_t j, original_varbinds_length; uint8_t repeater; uint8_t i, varbinds_length; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = 0; while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) { memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t)); original_varbinds_length++; } varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->non_repeaters) { break; } resource = snmp_mib_find_next(&oids[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; } else { return -1; } } } for(i = 0; i < header->max_repetitions; i++) { repeater = 0; for(j = header->non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(&oids[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = varbinds_length + 1; break; case SNMP_VERSION_2C: if(varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t)); (varbinds_length)++; } else { return -1; } break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t)); repeater++; } else { return -1; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine(snmp_packet_t *snmp_packet) { snmp_header_t header; snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; memset(&header, 0, sizeof(header)); memset(varbinds, 0, sizeof(varbinds)); if(!snmp_message_decode(snmp_packet, &header, varbinds)) { return 0; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return 0; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case BER_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds) == -1) { return 0; } break; default: LOG_ERR("Invalid request type"); return 0; } header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE; return snmp_message_encode(snmp_packet, &header, varbinds); }
snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; }
snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; }
{'added': [(2, ' * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * SNMP Implementation of the protocol engine'), (45, '#include "snmp-ber.h"'), (51, 'static inline int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds)'), (55, ' uint8_t i;'), (57, ' i = 0;'), (58, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (59, ' resource = snmp_mib_find(&varbinds[i].oid);'), (63, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (67, ' header->error_index = i + 1;'), (70, ' (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;'), (73, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (74, ' header->error_index = 0;'), (77, ' resource->handler(&varbinds[i], &resource->oid);'), (79, ''), (80, ' i++;'), (86, 'static inline int'), (87, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)'), (90, ' uint8_t i;'), (92, ' i = 0;'), (93, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (94, ' resource = snmp_mib_find_next(&varbinds[i].oid);'), (98, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (102, ' header->error_index = i + 1;'), (105, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (108, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (109, ' header->error_index = 0;'), (112, ' resource->handler(&varbinds[i], &resource->oid);'), (114, ''), (115, ' i++;'), (121, 'static inline int'), (122, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)'), (125, ' snmp_oid_t oids[SNMP_MAX_NR_VALUES];'), (126, ' uint32_t j, original_varbinds_length;'), (128, ' uint8_t i, varbinds_length;'), (134, ' original_varbinds_length = 0;'), (135, ' while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {'), (136, ' memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));'), (137, ' original_varbinds_length++;'), (140, ' varbinds_length = 0;'), (142, ' if(i >= header->non_repeaters) {'), (146, ' resource = snmp_mib_find_next(&oids[i]);'), (150, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (154, ' header->error_index = i + 1;'), (157, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (160, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (161, ' header->error_index = 0;'), (164, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (165, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (166, ' (varbinds_length)++;'), (167, ' } else {'), (168, ' return -1;'), (173, ' for(i = 0; i < header->max_repetitions; i++) {'), (175, ' for(j = header->non_repeaters; j < original_varbinds_length; j++) {'), (176, ' resource = snmp_mib_find_next(&oids[j]);'), (180, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (184, ' header->error_index = varbinds_length + 1;'), (187, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (188, ' (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (189, ' memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));'), (190, ' (varbinds_length)++;'), (191, ' } else {'), (192, ' return -1;'), (196, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (197, ' header->error_index = 0;'), (200, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (201, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (202, ' (varbinds_length)++;'), (203, ' memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));'), (205, ' } else {'), (206, ' return -1;'), (218, 'int'), (219, 'snmp_engine(snmp_packet_t *snmp_packet)'), (221, ' snmp_header_t header;'), (222, ' snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (223, ''), (224, ' memset(&header, 0, sizeof(header));'), (225, ' memset(varbinds, 0, sizeof(varbinds));'), (227, ' if(!snmp_message_decode(snmp_packet, &header, varbinds)) {'), (228, ' return 0;'), (234, ' return 0;'), (242, ' case BER_DATA_TYPE_PDU_GET_REQUEST:'), (243, ' if(snmp_engine_get(&header, varbinds) == -1) {'), (244, ' return 0;'), (248, ' case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (249, ' if(snmp_engine_get_next(&header, varbinds) == -1) {'), (250, ' return 0;'), (254, ' case BER_DATA_TYPE_PDU_GET_BULK:'), (255, ' if(snmp_engine_get_bulk(&header, varbinds) == -1) {'), (256, ' return 0;'), (262, ' return 0;'), (265, ' header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;'), (267, ' return snmp_message_encode(snmp_packet, &header, varbinds);')], 'deleted': [(2, ' * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * An implementation of the Simple Network Management Protocol (RFC 3411-3418)'), (45, '#include "snmp-oid.h"'), (51, 'int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (55, ' uint32_t i;'), (57, ' for(i = 0; i < varbinds_length; i++) {'), (58, ' resource = snmp_mib_find(varbinds[i].oid);'), (62, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (66, ' header->error_index_max_repetitions.error_index = i + 1;'), (69, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;'), (72, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (73, ' header->error_index_max_repetitions.error_index = 0;'), (76, ' resource->handler(&varbinds[i], resource->oid);'), (83, 'int'), (84, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (87, ' uint32_t i;'), (89, ' for(i = 0; i < varbinds_length; i++) {'), (90, ' resource = snmp_mib_find_next(varbinds[i].oid);'), (94, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (98, ' header->error_index_max_repetitions.error_index = i + 1;'), (101, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (104, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (105, ' header->error_index_max_repetitions.error_index = 0;'), (108, ' resource->handler(&varbinds[i], resource->oid);'), (115, 'int'), (116, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)'), (119, ' uint32_t i, j, original_varbinds_length;'), (120, ' uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];'), (127, ' original_varbinds_length = *varbinds_length;'), (128, ' for(i = 0; i < original_varbinds_length; i++) {'), (129, ' snmp_oid_copy(oid[i], varbinds[i].oid);'), (132, ' *varbinds_length = 0;'), (134, ' if(i >= header->error_status_non_repeaters.non_repeaters) {'), (138, ' resource = snmp_mib_find_next(oid[i]);'), (142, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (146, ' header->error_index_max_repetitions.error_index = i + 1;'), (149, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (152, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (153, ' header->error_index_max_repetitions.error_index = 0;'), (156, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (157, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (158, ' (*varbinds_length)++;'), (163, ' for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {'), (165, ' for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {'), (166, ' resource = snmp_mib_find_next(oid[j]);'), (170, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (174, ' header->error_index_max_repetitions.error_index = *varbinds_length + 1;'), (177, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (178, ' (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (179, ' snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);'), (180, ' (*varbinds_length)++;'), (184, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (185, ' header->error_index_max_repetitions.error_index = 0;'), (188, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (189, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (190, ' (*varbinds_length)++;'), (191, ' snmp_oid_copy(oid[j], resource->oid);'), (204, 'unsigned char *'), (205, 'snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)'), (207, ' static snmp_header_t header;'), (208, ' static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (209, ' static uint32_t varbind_length = SNMP_MAX_NR_VALUES;'), (211, ' buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);'), (212, ' if(buff == NULL) {'), (213, ' return NULL;'), (219, ' return NULL;'), (227, ' case SNMP_DATA_TYPE_PDU_GET_REQUEST:'), (228, ' if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {'), (229, ' return NULL;'), (233, ' case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (234, ' if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {'), (235, ' return NULL;'), (239, ' case SNMP_DATA_TYPE_PDU_GET_BULK:'), (240, ' if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {'), (241, ' return NULL;'), (247, ' return NULL;'), (250, ' header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;'), (251, ' out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);'), (253, ' return ++out;')]}
94
80
181
966
https://github.com/contiki-ng/contiki-ng
CVE-2020-12141
['CWE-125']
snmp-engine.c
snmp_engine_get_bulk
/* * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * An implementation of the Simple Network Management Protocol (RFC 3411-3418) * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-oid.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length) { snmp_mib_resource_t *resource; uint32_t i, j, original_varbinds_length; uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN]; uint8_t repeater; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = *varbinds_length; for(i = 0; i < original_varbinds_length; i++) { snmp_oid_copy(oid[i], varbinds[i].oid); } *varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->error_status_non_repeaters.non_repeaters) { break; } resource = snmp_mib_find_next(oid[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; } } } for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) { repeater = 0; for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(oid[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = *varbinds_length + 1; break; case SNMP_VERSION_2C: if(*varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]); (*varbinds_length)++; } break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; snmp_oid_copy(oid[j], resource->oid); repeater++; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ unsigned char * snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len) { static snmp_header_t header; static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; static uint32_t varbind_length = SNMP_MAX_NR_VALUES; buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length); if(buff == NULL) { return NULL; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return NULL; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case SNMP_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) { return NULL; } break; default: LOG_ERR("Invalid request type"); return NULL; } header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE; out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length); return ++out; }
/* * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * SNMP Implementation of the protocol engine * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-ber.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; snmp_oid_t oids[SNMP_MAX_NR_VALUES]; uint32_t j, original_varbinds_length; uint8_t repeater; uint8_t i, varbinds_length; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = 0; while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) { memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t)); original_varbinds_length++; } varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->non_repeaters) { break; } resource = snmp_mib_find_next(&oids[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; } else { return -1; } } } for(i = 0; i < header->max_repetitions; i++) { repeater = 0; for(j = header->non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(&oids[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = varbinds_length + 1; break; case SNMP_VERSION_2C: if(varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t)); (varbinds_length)++; } else { return -1; } break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t)); repeater++; } else { return -1; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine(snmp_packet_t *snmp_packet) { snmp_header_t header; snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; memset(&header, 0, sizeof(header)); memset(varbinds, 0, sizeof(varbinds)); if(!snmp_message_decode(snmp_packet, &header, varbinds)) { return 0; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return 0; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case BER_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds) == -1) { return 0; } break; default: LOG_ERR("Invalid request type"); return 0; } header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE; return snmp_message_encode(snmp_packet, &header, varbinds); }
snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length) { snmp_mib_resource_t *resource; uint32_t i, j, original_varbinds_length; uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN]; uint8_t repeater; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = *varbinds_length; for(i = 0; i < original_varbinds_length; i++) { snmp_oid_copy(oid[i], varbinds[i].oid); } *varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->error_status_non_repeaters.non_repeaters) { break; } resource = snmp_mib_find_next(oid[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; } } } for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) { repeater = 0; for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(oid[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = *varbinds_length + 1; break; case SNMP_VERSION_2C: if(*varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]); (*varbinds_length)++; } break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; snmp_oid_copy(oid[j], resource->oid); repeater++; } } } if(repeater == 0) { break; } } return 0; }
snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; snmp_oid_t oids[SNMP_MAX_NR_VALUES]; uint32_t j, original_varbinds_length; uint8_t repeater; uint8_t i, varbinds_length; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = 0; while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) { memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t)); original_varbinds_length++; } varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->non_repeaters) { break; } resource = snmp_mib_find_next(&oids[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; } else { return -1; } } } for(i = 0; i < header->max_repetitions; i++) { repeater = 0; for(j = header->non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(&oids[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = varbinds_length + 1; break; case SNMP_VERSION_2C: if(varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t)); (varbinds_length)++; } else { return -1; } break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t)); repeater++; } else { return -1; } } } if(repeater == 0) { break; } } return 0; }
{'added': [(2, ' * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * SNMP Implementation of the protocol engine'), (45, '#include "snmp-ber.h"'), (51, 'static inline int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds)'), (55, ' uint8_t i;'), (57, ' i = 0;'), (58, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (59, ' resource = snmp_mib_find(&varbinds[i].oid);'), (63, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (67, ' header->error_index = i + 1;'), (70, ' (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;'), (73, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (74, ' header->error_index = 0;'), (77, ' resource->handler(&varbinds[i], &resource->oid);'), (79, ''), (80, ' i++;'), (86, 'static inline int'), (87, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)'), (90, ' uint8_t i;'), (92, ' i = 0;'), (93, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (94, ' resource = snmp_mib_find_next(&varbinds[i].oid);'), (98, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (102, ' header->error_index = i + 1;'), (105, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (108, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (109, ' header->error_index = 0;'), (112, ' resource->handler(&varbinds[i], &resource->oid);'), (114, ''), (115, ' i++;'), (121, 'static inline int'), (122, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)'), (125, ' snmp_oid_t oids[SNMP_MAX_NR_VALUES];'), (126, ' uint32_t j, original_varbinds_length;'), (128, ' uint8_t i, varbinds_length;'), (134, ' original_varbinds_length = 0;'), (135, ' while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {'), (136, ' memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));'), (137, ' original_varbinds_length++;'), (140, ' varbinds_length = 0;'), (142, ' if(i >= header->non_repeaters) {'), (146, ' resource = snmp_mib_find_next(&oids[i]);'), (150, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (154, ' header->error_index = i + 1;'), (157, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (160, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (161, ' header->error_index = 0;'), (164, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (165, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (166, ' (varbinds_length)++;'), (167, ' } else {'), (168, ' return -1;'), (173, ' for(i = 0; i < header->max_repetitions; i++) {'), (175, ' for(j = header->non_repeaters; j < original_varbinds_length; j++) {'), (176, ' resource = snmp_mib_find_next(&oids[j]);'), (180, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (184, ' header->error_index = varbinds_length + 1;'), (187, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (188, ' (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (189, ' memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));'), (190, ' (varbinds_length)++;'), (191, ' } else {'), (192, ' return -1;'), (196, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (197, ' header->error_index = 0;'), (200, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (201, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (202, ' (varbinds_length)++;'), (203, ' memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));'), (205, ' } else {'), (206, ' return -1;'), (218, 'int'), (219, 'snmp_engine(snmp_packet_t *snmp_packet)'), (221, ' snmp_header_t header;'), (222, ' snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (223, ''), (224, ' memset(&header, 0, sizeof(header));'), (225, ' memset(varbinds, 0, sizeof(varbinds));'), (227, ' if(!snmp_message_decode(snmp_packet, &header, varbinds)) {'), (228, ' return 0;'), (234, ' return 0;'), (242, ' case BER_DATA_TYPE_PDU_GET_REQUEST:'), (243, ' if(snmp_engine_get(&header, varbinds) == -1) {'), (244, ' return 0;'), (248, ' case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (249, ' if(snmp_engine_get_next(&header, varbinds) == -1) {'), (250, ' return 0;'), (254, ' case BER_DATA_TYPE_PDU_GET_BULK:'), (255, ' if(snmp_engine_get_bulk(&header, varbinds) == -1) {'), (256, ' return 0;'), (262, ' return 0;'), (265, ' header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;'), (267, ' return snmp_message_encode(snmp_packet, &header, varbinds);')], 'deleted': [(2, ' * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * An implementation of the Simple Network Management Protocol (RFC 3411-3418)'), (45, '#include "snmp-oid.h"'), (51, 'int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (55, ' uint32_t i;'), (57, ' for(i = 0; i < varbinds_length; i++) {'), (58, ' resource = snmp_mib_find(varbinds[i].oid);'), (62, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (66, ' header->error_index_max_repetitions.error_index = i + 1;'), (69, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;'), (72, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (73, ' header->error_index_max_repetitions.error_index = 0;'), (76, ' resource->handler(&varbinds[i], resource->oid);'), (83, 'int'), (84, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (87, ' uint32_t i;'), (89, ' for(i = 0; i < varbinds_length; i++) {'), (90, ' resource = snmp_mib_find_next(varbinds[i].oid);'), (94, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (98, ' header->error_index_max_repetitions.error_index = i + 1;'), (101, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (104, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (105, ' header->error_index_max_repetitions.error_index = 0;'), (108, ' resource->handler(&varbinds[i], resource->oid);'), (115, 'int'), (116, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)'), (119, ' uint32_t i, j, original_varbinds_length;'), (120, ' uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];'), (127, ' original_varbinds_length = *varbinds_length;'), (128, ' for(i = 0; i < original_varbinds_length; i++) {'), (129, ' snmp_oid_copy(oid[i], varbinds[i].oid);'), (132, ' *varbinds_length = 0;'), (134, ' if(i >= header->error_status_non_repeaters.non_repeaters) {'), (138, ' resource = snmp_mib_find_next(oid[i]);'), (142, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (146, ' header->error_index_max_repetitions.error_index = i + 1;'), (149, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (152, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (153, ' header->error_index_max_repetitions.error_index = 0;'), (156, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (157, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (158, ' (*varbinds_length)++;'), (163, ' for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {'), (165, ' for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {'), (166, ' resource = snmp_mib_find_next(oid[j]);'), (170, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (174, ' header->error_index_max_repetitions.error_index = *varbinds_length + 1;'), (177, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (178, ' (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (179, ' snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);'), (180, ' (*varbinds_length)++;'), (184, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (185, ' header->error_index_max_repetitions.error_index = 0;'), (188, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (189, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (190, ' (*varbinds_length)++;'), (191, ' snmp_oid_copy(oid[j], resource->oid);'), (204, 'unsigned char *'), (205, 'snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)'), (207, ' static snmp_header_t header;'), (208, ' static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (209, ' static uint32_t varbind_length = SNMP_MAX_NR_VALUES;'), (211, ' buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);'), (212, ' if(buff == NULL) {'), (213, ' return NULL;'), (219, ' return NULL;'), (227, ' case SNMP_DATA_TYPE_PDU_GET_REQUEST:'), (228, ' if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {'), (229, ' return NULL;'), (233, ' case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (234, ' if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {'), (235, ' return NULL;'), (239, ' case SNMP_DATA_TYPE_PDU_GET_BULK:'), (240, ' if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {'), (241, ' return NULL;'), (247, ' return NULL;'), (250, ' header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;'), (251, ' out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);'), (253, ' return ++out;')]}
94
80
181
966
https://github.com/contiki-ng/contiki-ng
CVE-2020-12141
['CWE-125']
snmp-engine.c
snmp_engine_get_next
/* * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * An implementation of the Simple Network Management Protocol (RFC 3411-3418) * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-oid.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length) { snmp_mib_resource_t *resource; uint32_t i, j, original_varbinds_length; uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN]; uint8_t repeater; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = *varbinds_length; for(i = 0; i < original_varbinds_length; i++) { snmp_oid_copy(oid[i], varbinds[i].oid); } *varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->error_status_non_repeaters.non_repeaters) { break; } resource = snmp_mib_find_next(oid[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; } } } for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) { repeater = 0; for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(oid[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = *varbinds_length + 1; break; case SNMP_VERSION_2C: if(*varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]); (*varbinds_length)++; } break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { if(*varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[*varbinds_length], resource->oid); (*varbinds_length)++; snmp_oid_copy(oid[j], resource->oid); repeater++; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ unsigned char * snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len) { static snmp_header_t header; static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; static uint32_t varbind_length = SNMP_MAX_NR_VALUES; buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length); if(buff == NULL) { return NULL; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return NULL; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case SNMP_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) { return NULL; } break; case SNMP_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) { return NULL; } break; default: LOG_ERR("Invalid request type"); return NULL; } header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE; out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length); return ++out; }
/* * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /*---------------------------------------------------------------------------*/ /** * \file * SNMP Implementation of the protocol engine * \author * Yago Fontoura do Rosario <yago.rosario@hotmail.com.br */ #include "contiki.h" #include "snmp-engine.h" #include "snmp-message.h" #include "snmp-mib.h" #include "snmp-ber.h" #define LOG_MODULE "SNMP [engine]" #define LOG_LEVEL LOG_LEVEL_SNMP /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; } /*---------------------------------------------------------------------------*/ static inline int snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; snmp_oid_t oids[SNMP_MAX_NR_VALUES]; uint32_t j, original_varbinds_length; uint8_t repeater; uint8_t i, varbinds_length; /* * A local copy of the requested oids must be kept since * the varbinds are modified on the fly */ original_varbinds_length = 0; while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) { memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t)); original_varbinds_length++; } varbinds_length = 0; for(i = 0; i < original_varbinds_length; i++) { if(i >= header->non_repeaters) { break; } resource = snmp_mib_find_next(&oids[i]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; } else { return -1; } } } for(i = 0; i < header->max_repetitions; i++) { repeater = 0; for(j = header->non_repeaters; j < original_varbinds_length; j++) { resource = snmp_mib_find_next(&oids[j]); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = varbinds_length + 1; break; case SNMP_VERSION_2C: if(varbinds_length < SNMP_MAX_NR_VALUES) { (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t)); (varbinds_length)++; } else { return -1; } break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { if(varbinds_length < SNMP_MAX_NR_VALUES) { resource->handler(&varbinds[varbinds_length], &resource->oid); (varbinds_length)++; memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t)); repeater++; } else { return -1; } } } if(repeater == 0) { break; } } return 0; } /*---------------------------------------------------------------------------*/ int snmp_engine(snmp_packet_t *snmp_packet) { snmp_header_t header; snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES]; memset(&header, 0, sizeof(header)); memset(varbinds, 0, sizeof(varbinds)); if(!snmp_message_decode(snmp_packet, &header, varbinds)) { return 0; } if(header.version != SNMP_VERSION_1) { if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) { LOG_ERR("Request with invalid community\n"); return 0; } } /* * Now handle the SNMP requests depending on their type */ switch(header.pdu_type) { case BER_DATA_TYPE_PDU_GET_REQUEST: if(snmp_engine_get(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST: if(snmp_engine_get_next(&header, varbinds) == -1) { return 0; } break; case BER_DATA_TYPE_PDU_GET_BULK: if(snmp_engine_get_bulk(&header, varbinds) == -1) { return 0; } break; default: LOG_ERR("Invalid request type"); return 0; } header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE; return snmp_message_encode(snmp_packet, &header, varbinds); }
snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length) { snmp_mib_resource_t *resource; uint32_t i; for(i = 0; i < varbinds_length; i++) { resource = snmp_mib_find_next(varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index_max_repetitions.error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index_max_repetitions.error_index = 0; } } else { resource->handler(&varbinds[i], resource->oid); } } return 0; }
snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds) { snmp_mib_resource_t *resource; uint8_t i; i = 0; while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) { resource = snmp_mib_find_next(&varbinds[i].oid); if(!resource) { switch(header->version) { case SNMP_VERSION_1: header->error_status = SNMP_STATUS_NO_SUCH_NAME; /* * Varbinds are 1 indexed */ header->error_index = i + 1; break; case SNMP_VERSION_2C: (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW; break; default: header->error_status = SNMP_STATUS_NO_SUCH_NAME; header->error_index = 0; } } else { resource->handler(&varbinds[i], &resource->oid); } i++; } return 0; }
{'added': [(2, ' * Copyright (C) 2019-2020 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * SNMP Implementation of the protocol engine'), (45, '#include "snmp-ber.h"'), (51, 'static inline int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds)'), (55, ' uint8_t i;'), (57, ' i = 0;'), (58, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (59, ' resource = snmp_mib_find(&varbinds[i].oid);'), (63, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (67, ' header->error_index = i + 1;'), (70, ' (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;'), (73, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (74, ' header->error_index = 0;'), (77, ' resource->handler(&varbinds[i], &resource->oid);'), (79, ''), (80, ' i++;'), (86, 'static inline int'), (87, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)'), (90, ' uint8_t i;'), (92, ' i = 0;'), (93, ' while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {'), (94, ' resource = snmp_mib_find_next(&varbinds[i].oid);'), (98, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (102, ' header->error_index = i + 1;'), (105, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (108, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (109, ' header->error_index = 0;'), (112, ' resource->handler(&varbinds[i], &resource->oid);'), (114, ''), (115, ' i++;'), (121, 'static inline int'), (122, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)'), (125, ' snmp_oid_t oids[SNMP_MAX_NR_VALUES];'), (126, ' uint32_t j, original_varbinds_length;'), (128, ' uint8_t i, varbinds_length;'), (134, ' original_varbinds_length = 0;'), (135, ' while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {'), (136, ' memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));'), (137, ' original_varbinds_length++;'), (140, ' varbinds_length = 0;'), (142, ' if(i >= header->non_repeaters) {'), (146, ' resource = snmp_mib_find_next(&oids[i]);'), (150, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (154, ' header->error_index = i + 1;'), (157, ' (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (160, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (161, ' header->error_index = 0;'), (164, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (165, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (166, ' (varbinds_length)++;'), (167, ' } else {'), (168, ' return -1;'), (173, ' for(i = 0; i < header->max_repetitions; i++) {'), (175, ' for(j = header->non_repeaters; j < original_varbinds_length; j++) {'), (176, ' resource = snmp_mib_find_next(&oids[j]);'), (180, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (184, ' header->error_index = varbinds_length + 1;'), (187, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (188, ' (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;'), (189, ' memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));'), (190, ' (varbinds_length)++;'), (191, ' } else {'), (192, ' return -1;'), (196, ' header->error_status = SNMP_STATUS_NO_SUCH_NAME;'), (197, ' header->error_index = 0;'), (200, ' if(varbinds_length < SNMP_MAX_NR_VALUES) {'), (201, ' resource->handler(&varbinds[varbinds_length], &resource->oid);'), (202, ' (varbinds_length)++;'), (203, ' memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));'), (205, ' } else {'), (206, ' return -1;'), (218, 'int'), (219, 'snmp_engine(snmp_packet_t *snmp_packet)'), (221, ' snmp_header_t header;'), (222, ' snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (223, ''), (224, ' memset(&header, 0, sizeof(header));'), (225, ' memset(varbinds, 0, sizeof(varbinds));'), (227, ' if(!snmp_message_decode(snmp_packet, &header, varbinds)) {'), (228, ' return 0;'), (234, ' return 0;'), (242, ' case BER_DATA_TYPE_PDU_GET_REQUEST:'), (243, ' if(snmp_engine_get(&header, varbinds) == -1) {'), (244, ' return 0;'), (248, ' case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (249, ' if(snmp_engine_get_next(&header, varbinds) == -1) {'), (250, ' return 0;'), (254, ' case BER_DATA_TYPE_PDU_GET_BULK:'), (255, ' if(snmp_engine_get_bulk(&header, varbinds) == -1) {'), (256, ' return 0;'), (262, ' return 0;'), (265, ' header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;'), (267, ' return snmp_message_encode(snmp_packet, &header, varbinds);')], 'deleted': [(2, ' * Copyright (C) 2019 Yago Fontoura do Rosario <yago.rosario@hotmail.com.br>'), (35, ' * An implementation of the Simple Network Management Protocol (RFC 3411-3418)'), (45, '#include "snmp-oid.h"'), (51, 'int'), (52, 'snmp_engine_get(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (55, ' uint32_t i;'), (57, ' for(i = 0; i < varbinds_length; i++) {'), (58, ' resource = snmp_mib_find(varbinds[i].oid);'), (62, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (66, ' header->error_index_max_repetitions.error_index = i + 1;'), (69, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;'), (72, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (73, ' header->error_index_max_repetitions.error_index = 0;'), (76, ' resource->handler(&varbinds[i], resource->oid);'), (83, 'int'), (84, 'snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)'), (87, ' uint32_t i;'), (89, ' for(i = 0; i < varbinds_length; i++) {'), (90, ' resource = snmp_mib_find_next(varbinds[i].oid);'), (94, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (98, ' header->error_index_max_repetitions.error_index = i + 1;'), (101, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (104, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (105, ' header->error_index_max_repetitions.error_index = 0;'), (108, ' resource->handler(&varbinds[i], resource->oid);'), (115, 'int'), (116, 'snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)'), (119, ' uint32_t i, j, original_varbinds_length;'), (120, ' uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];'), (127, ' original_varbinds_length = *varbinds_length;'), (128, ' for(i = 0; i < original_varbinds_length; i++) {'), (129, ' snmp_oid_copy(oid[i], varbinds[i].oid);'), (132, ' *varbinds_length = 0;'), (134, ' if(i >= header->error_status_non_repeaters.non_repeaters) {'), (138, ' resource = snmp_mib_find_next(oid[i]);'), (142, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (146, ' header->error_index_max_repetitions.error_index = i + 1;'), (149, ' (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (152, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (153, ' header->error_index_max_repetitions.error_index = 0;'), (156, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (157, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (158, ' (*varbinds_length)++;'), (163, ' for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {'), (165, ' for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {'), (166, ' resource = snmp_mib_find_next(oid[j]);'), (170, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (174, ' header->error_index_max_repetitions.error_index = *varbinds_length + 1;'), (177, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (178, ' (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;'), (179, ' snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);'), (180, ' (*varbinds_length)++;'), (184, ' header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;'), (185, ' header->error_index_max_repetitions.error_index = 0;'), (188, ' if(*varbinds_length < SNMP_MAX_NR_VALUES) {'), (189, ' resource->handler(&varbinds[*varbinds_length], resource->oid);'), (190, ' (*varbinds_length)++;'), (191, ' snmp_oid_copy(oid[j], resource->oid);'), (204, 'unsigned char *'), (205, 'snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)'), (207, ' static snmp_header_t header;'), (208, ' static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];'), (209, ' static uint32_t varbind_length = SNMP_MAX_NR_VALUES;'), (211, ' buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);'), (212, ' if(buff == NULL) {'), (213, ' return NULL;'), (219, ' return NULL;'), (227, ' case SNMP_DATA_TYPE_PDU_GET_REQUEST:'), (228, ' if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {'), (229, ' return NULL;'), (233, ' case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:'), (234, ' if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {'), (235, ' return NULL;'), (239, ' case SNMP_DATA_TYPE_PDU_GET_BULK:'), (240, ' if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {'), (241, ' return NULL;'), (247, ' return NULL;'), (250, ' header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;'), (251, ' out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);'), (253, ' return ++out;')]}
94
80
181
966
https://github.com/contiki-ng/contiki-ng
CVE-2020-12141
['CWE-125']
ndpi_main.c
ndpi_reset_packet_line_info
/* * ndpi_main.c * * Copyright (C) 2011-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include <stdlib.h> #include <errno.h> #include <sys/types.h> #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_UNKNOWN #include "ndpi_config.h" #include "ndpi_api.h" #include "ahocorasick.h" #include "libcache.h" #include <time.h> #ifndef WIN32 #include <unistd.h> #endif #if defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ #include <sys/endian.h> #endif #include "ndpi_content_match.c.inc" #include "third_party/include/ndpi_patricia.h" #include "third_party/include/ht_hash.h" #include "third_party/include/ndpi_md5.h" /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static int _ndpi_debug_callbacks = 0; /* #define MATCH_DEBUG 1 */ /* ****************************************** */ static void *(*_ndpi_flow_malloc)(size_t size); static void (*_ndpi_flow_free)(void *ptr); static void *(*_ndpi_malloc)(size_t size); static void (*_ndpi_free)(void *ptr); /* ****************************************** */ /* Forward */ static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range, ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root, const char *_func, int _line); static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root); /* ****************************************** */ static inline uint8_t flow_is_proto(struct ndpi_flow_struct *flow, u_int16_t p) { return((flow->detected_protocol_stack[0] == p) || (flow->detected_protocol_stack[1] == p)); } /* ****************************************** */ void *ndpi_malloc(size_t size) { return(_ndpi_malloc ? _ndpi_malloc(size) : malloc(size)); } void *ndpi_flow_malloc(size_t size) { return(_ndpi_flow_malloc ? _ndpi_flow_malloc(size) : ndpi_malloc(size)); } /* ****************************************** */ void *ndpi_calloc(unsigned long count, size_t size) { size_t len = count * size; void *p = ndpi_malloc(len); if(p) memset(p, 0, len); return(p); } /* ****************************************** */ void ndpi_free(void *ptr) { if(_ndpi_free) _ndpi_free(ptr); else free(ptr); } /* ****************************************** */ void ndpi_flow_free(void *ptr) { if(_ndpi_flow_free) _ndpi_flow_free(ptr); else ndpi_free_flow((struct ndpi_flow_struct *) ptr); } /* ****************************************** */ void *ndpi_realloc(void *ptr, size_t old_size, size_t new_size) { void *ret = ndpi_malloc(new_size); if(!ret) return(ret); else { memcpy(ret, ptr, old_size); ndpi_free(ptr); return(ret); } } /* ****************************************** */ char *ndpi_strdup(const char *s) { if(s == NULL ){ return NULL; } int len = strlen(s); char *m = ndpi_malloc(len + 1); if(m) { memcpy(m, s, len); m[len] = '\0'; } return(m); } /* *********************************************************************************** */ /* Opaque structure defined here */ struct ndpi_ptree { patricia_tree_t *v4; patricia_tree_t *v6; }; /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_struct(void) { return(sizeof(struct ndpi_flow_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_id_struct(void) { return(sizeof(struct ndpi_id_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_tcp_struct(void) { return(sizeof(struct ndpi_flow_tcp_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_udp_struct(void) { return(sizeof(struct ndpi_flow_udp_struct)); } /* *********************************************************************************** */ char *ndpi_get_proto_by_id(struct ndpi_detection_module_struct *ndpi_str, u_int id) { return((id >= ndpi_str->ndpi_num_supported_protocols) ? NULL : ndpi_str->proto_defaults[id].protoName); } /* *********************************************************************************** */ u_int16_t ndpi_get_proto_by_name(struct ndpi_detection_module_struct *ndpi_str, const char *name) { u_int16_t i, num = ndpi_get_num_supported_protocols(ndpi_str); for (i = 0; i < num; i++) if(strcasecmp(ndpi_get_proto_by_id(ndpi_str, i), name) == 0) return(i); return(NDPI_PROTOCOL_UNKNOWN); } /* ************************************************************************************* */ #ifdef CODE_UNUSED ndpi_port_range *ndpi_build_default_ports_range(ndpi_port_range *ports, u_int16_t portA_low, u_int16_t portA_high, u_int16_t portB_low, u_int16_t portB_high, u_int16_t portC_low, u_int16_t portC_high, u_int16_t portD_low, u_int16_t portD_high, u_int16_t portE_low, u_int16_t portE_high) { int i = 0; ports[i].port_low = portA_low, ports[i].port_high = portA_high; i++; ports[i].port_low = portB_low, ports[i].port_high = portB_high; i++; ports[i].port_low = portC_low, ports[i].port_high = portC_high; i++; ports[i].port_low = portD_low, ports[i].port_high = portD_high; i++; ports[i].port_low = portE_low, ports[i].port_high = portE_high; return(ports); } #endif /* *********************************************************************************** */ ndpi_port_range *ndpi_build_default_ports(ndpi_port_range *ports, u_int16_t portA, u_int16_t portB, u_int16_t portC, u_int16_t portD, u_int16_t portE) { int i = 0; ports[i].port_low = portA, ports[i].port_high = portA; i++; ports[i].port_low = portB, ports[i].port_high = portB; i++; ports[i].port_low = portC, ports[i].port_high = portC; i++; ports[i].port_low = portD, ports[i].port_high = portD; i++; ports[i].port_low = portE, ports[i].port_high = portE; return(ports); } /* ********************************************************************************** */ void ndpi_set_proto_breed(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId, ndpi_protocol_breed_t breed) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return; else ndpi_str->proto_defaults[protoId].protoBreed = breed; } /* ********************************************************************************** */ void ndpi_set_proto_category(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId, ndpi_protocol_category_t protoCategory) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return; else ndpi_str->proto_defaults[protoId].protoCategory = protoCategory; } /* ********************************************************************************** */ /* There are some (master) protocols that are informative, meaning that it shows what is the subprotocol about, but also that the subprotocol isn't a real protocol. Example: - DNS is informative as if we see a DNS request for www.facebook.com, the returned protocol is DNS.Facebook, but Facebook isn't a real subprotocol but rather it indicates a query for Facebook and not Facebook traffic. - HTTP/SSL are NOT informative as SSL.Facebook (likely) means that this is SSL (HTTPS) traffic containg Facebook traffic. */ u_int8_t ndpi_is_subprotocol_informative(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return(0); switch (protoId) { /* All dissectors that have calls to ndpi_match_host_subprotocol() */ case NDPI_PROTOCOL_DNS: return(1); break; default: return(0); } } /* ********************************************************************************** */ void ndpi_exclude_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t protocol_id, const char *_file, const char *_func, int _line) { if(protocol_id < NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES if(ndpi_str && ndpi_str->ndpi_log_level >= NDPI_LOG_DEBUG && ndpi_str->ndpi_debug_printf != NULL) { (*(ndpi_str->ndpi_debug_printf))(protocol_id, ndpi_str, NDPI_LOG_DEBUG, _file, _func, _line, "exclude %s\n", ndpi_get_proto_name(ndpi_str, protocol_id)); } #endif NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, protocol_id); } } /* ********************************************************************************** */ void ndpi_set_proto_defaults(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_breed_t breed, u_int16_t protoId, u_int8_t can_have_a_subprotocol, u_int16_t tcp_master_protoId[2], u_int16_t udp_master_protoId[2], char *protoName, ndpi_protocol_category_t protoCategory, ndpi_port_range *tcpDefPorts, ndpi_port_range *udpDefPorts) { char *name; int j; if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) { #ifdef DEBUG NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: INTERNAL ERROR\n", protoName, protoId); #endif return; } if(ndpi_str->proto_defaults[protoId].protoName != NULL) { #ifdef DEBUG NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: already initialized. Ignoring it\n", protoName, protoId); #endif return; } name = ndpi_strdup(protoName); if(ndpi_str->proto_defaults[protoId].protoName) ndpi_free(ndpi_str->proto_defaults[protoId].protoName); ndpi_str->proto_defaults[protoId].protoName = name, ndpi_str->proto_defaults[protoId].protoCategory = protoCategory, ndpi_str->proto_defaults[protoId].protoId = protoId, ndpi_str->proto_defaults[protoId].protoBreed = breed; ndpi_str->proto_defaults[protoId].can_have_a_subprotocol = can_have_a_subprotocol; memcpy(&ndpi_str->proto_defaults[protoId].master_tcp_protoId, tcp_master_protoId, 2 * sizeof(u_int16_t)); memcpy(&ndpi_str->proto_defaults[protoId].master_udp_protoId, udp_master_protoId, 2 * sizeof(u_int16_t)); for (j = 0; j < MAX_DEFAULT_PORTS; j++) { if(udpDefPorts[j].port_low != 0) addDefaultPort(ndpi_str, &udpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->udpRoot, __FUNCTION__, __LINE__); if(tcpDefPorts[j].port_low != 0) addDefaultPort(ndpi_str, &tcpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->tcpRoot, __FUNCTION__, __LINE__); /* No port range, just the lower port */ ndpi_str->proto_defaults[protoId].tcp_default_ports[j] = tcpDefPorts[j].port_low; ndpi_str->proto_defaults[protoId].udp_default_ports[j] = udpDefPorts[j].port_low; } } /* ******************************************************************** */ static int ndpi_default_ports_tree_node_t_cmp(const void *a, const void *b) { ndpi_default_ports_tree_node_t *fa = (ndpi_default_ports_tree_node_t *) a; ndpi_default_ports_tree_node_t *fb = (ndpi_default_ports_tree_node_t *) b; //printf("[NDPI] %s(%d, %d)\n", __FUNCTION__, fa->default_port, fb->default_port); return((fa->default_port == fb->default_port) ? 0 : ((fa->default_port < fb->default_port) ? -1 : 1)); } /* ******************************************************************** */ void ndpi_default_ports_tree_node_t_walker(const void *node, const ndpi_VISIT which, const int depth) { ndpi_default_ports_tree_node_t *f = *(ndpi_default_ports_tree_node_t **) node; printf("<%d>Walk on node %s (%u)\n", depth, which == ndpi_preorder ? "ndpi_preorder" : which == ndpi_postorder ? "ndpi_postorder" : which == ndpi_endorder ? "ndpi_endorder" : which == ndpi_leaf ? "ndpi_leaf" : "unknown", f->default_port); } /* ******************************************************************** */ static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range, ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root, const char *_func, int _line) { u_int16_t port; for (port = range->port_low; port <= range->port_high; port++) { ndpi_default_ports_tree_node_t *node = (ndpi_default_ports_tree_node_t *) ndpi_malloc(sizeof(ndpi_default_ports_tree_node_t)); ndpi_default_ports_tree_node_t *ret; if(!node) { NDPI_LOG_ERR(ndpi_str, "%s:%d not enough memory\n", _func, _line); break; } node->proto = def, node->default_port = port, node->customUserProto = customUserProto; ret = (ndpi_default_ports_tree_node_t *) ndpi_tsearch(node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */ if(ret != node) { NDPI_LOG_DBG(ndpi_str, "[NDPI] %s:%d found duplicate for port %u: overwriting it with new value\n", _func, _line, port); ret->proto = def; ndpi_free(node); } } } /* ****************************************************** */ /* NOTE This function must be called with a semaphore set, this in order to avoid changing the datastructures while using them */ static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root) { ndpi_default_ports_tree_node_t node; u_int16_t port; for (port = range->port_low; port <= range->port_high; port++) { ndpi_default_ports_tree_node_t *ret; node.proto = def, node.default_port = port; ret = (ndpi_default_ports_tree_node_t *) ndpi_tdelete( &node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */ if(ret != NULL) { ndpi_free((ndpi_default_ports_tree_node_t *) ret); return(0); } } return(-1); } /* ****************************************************** */ static int ndpi_string_to_automa(struct ndpi_detection_module_struct *ndpi_str, ndpi_automa *automa, char *value, u_int16_t protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed, u_int8_t free_str_on_duplicate) { AC_PATTERN_t ac_pattern; AC_ERROR_t rc; if((value == NULL) || (protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS))) { NDPI_LOG_ERR(ndpi_str, "[NDPI] protoId=%d: INTERNAL ERROR\n", protocol_id); return(-1); } if(automa->ac_automa == NULL) return(-2); ac_pattern.astring = value, ac_pattern.rep.number = protocol_id, ac_pattern.rep.category = (u_int16_t) category, ac_pattern.rep.breed = (u_int16_t) breed; #ifdef MATCH_DEBUG printf("Adding to automa [%s][protocol_id: %u][category: %u][breed: %u]\n", value, protocol_id, category, breed); #endif if(value == NULL) ac_pattern.length = 0; else ac_pattern.length = strlen(ac_pattern.astring); rc = ac_automata_add(((AC_AUTOMATA_t *) automa->ac_automa), &ac_pattern); if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS) return(-2); if(rc == ACERR_DUPLICATE_PATTERN && free_str_on_duplicate) ndpi_free(value); return(0); } /* ****************************************************** */ static int ndpi_add_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *_value, int protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) { int rv; char *value = ndpi_strdup(_value); if(!value) return(-1); #ifdef DEBUG NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding [%s][%d]\n", value, protocol_id); #endif rv = ndpi_string_to_automa(ndpi_str, &ndpi_str->host_automa, value, protocol_id, category, breed, 1); if(rv != 0) ndpi_free(value); return(rv); } /* ****************************************************** */ #ifdef CODE_UNUSED int ndpi_add_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) { return(ndpi_string_to_automa(ndpi_str, &ndpi_str->content_automa, value, protocol_id, category, breed, 0)); } #endif /* ****************************************************** */ /* NOTE This function must be called with a semaphore set, this in order to avoid changing the datastructures while using them */ static int ndpi_remove_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id) { NDPI_LOG_ERR(ndpi_str, "[NDPI] Missing implementation for proto %s/%d\n", value, protocol_id); return(-1); } /* ******************************************************************** */ void ndpi_init_protocol_match(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_match *match) { u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}; ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; if(ndpi_str->proto_defaults[match->protocol_id].protoName == NULL) { ndpi_str->proto_defaults[match->protocol_id].protoName = ndpi_strdup(match->proto_name); ndpi_str->proto_defaults[match->protocol_id].protoId = match->protocol_id; ndpi_str->proto_defaults[match->protocol_id].protoCategory = match->protocol_category; ndpi_str->proto_defaults[match->protocol_id].protoBreed = match->protocol_breed; ndpi_set_proto_defaults(ndpi_str, ndpi_str->proto_defaults[match->protocol_id].protoBreed, ndpi_str->proto_defaults[match->protocol_id].protoId, 0 /* can_have_a_subprotocol */, no_master, no_master, ndpi_str->proto_defaults[match->protocol_id].protoName, ndpi_str->proto_defaults[match->protocol_id].protoCategory, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); } ndpi_add_host_url_subprotocol(ndpi_str, match->string_to_match, match->protocol_id, match->protocol_category, match->protocol_breed); } /* ******************************************************************** */ /* Self check function to be called onli for testing purposes */ void ndpi_self_check_host_match() { u_int32_t i, j; for (i = 0; host_match[i].string_to_match != NULL; i++) { for (j = 0; host_match[j].string_to_match != NULL; j++) { if((i != j) && (strcmp(host_match[i].string_to_match, host_match[j].string_to_match) == 0)) { printf("[INTERNAL ERROR]: Duplicate string detected '%s' [id: %u, id %u]\n", host_match[i].string_to_match, i, j); printf("\nPlease fix host_match[] in ndpi_content_match.c.inc\n"); exit(0); } } } } /* ******************************************************************** */ static void init_string_based_protocols(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; host_match[i].string_to_match != NULL; i++) ndpi_init_protocol_match(ndpi_str, &host_match[i]); ndpi_enable_loaded_categories(ndpi_str); #ifdef MATCH_DEBUG // ac_automata_display(ndpi_str->host_automa.ac_automa, 'n'); #endif #if 1 for (i = 0; ndpi_en_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->bigrams_automa, (char *) ndpi_en_bigrams[i], 1, 1, 1, 0); #else for (i = 0; ndpi_en_popular_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->bigrams_automa, (char *) ndpi_en_popular_bigrams[i], 1, 1, 1, 0); #endif for (i = 0; ndpi_en_impossible_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->impossible_bigrams_automa, (char *) ndpi_en_impossible_bigrams[i], 1, 1, 1, 0); } /* ******************************************************************** */ int ndpi_set_detection_preferences(struct ndpi_detection_module_struct *ndpi_str, ndpi_detection_preference pref, int value) { switch (pref) { case ndpi_pref_direction_detect_disable: ndpi_str->direction_detect_disable = (u_int8_t) value; break; default: return(-1); } return(0); } /* ******************************************************************** */ static void ndpi_validate_protocol_initialization(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) { if(ndpi_str->proto_defaults[i].protoName == NULL) { NDPI_LOG_ERR(ndpi_str, "[NDPI] INTERNAL ERROR missing protoName initialization for [protoId=%d]: recovering\n", i); } else { if((i != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[i].protoCategory == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) { NDPI_LOG_ERR(ndpi_str, "[NDPI] INTERNAL ERROR missing category [protoId=%d/%s] initialization: recovering\n", i, ndpi_str->proto_defaults[i].protoName ? ndpi_str->proto_defaults[i].protoName : "???"); } } } } /* ******************************************************************** */ /* This function is used to map protocol name and default ports and it MUST be updated whenever a new protocol is added to NDPI. Do NOT add web services (NDPI_SERVICE_xxx) here. */ static void ndpi_init_protocol_defaults(struct ndpi_detection_module_struct *ndpi_str) { ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}, custom_master[2]; /* Reset all settings */ memset(ndpi_str->proto_defaults, 0, sizeof(ndpi_str->proto_defaults)); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNRATED, NDPI_PROTOCOL_UNKNOWN, 0 /* can_have_a_subprotocol */, no_master, no_master, "Unknown", NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_FTP_CONTROL, 0 /* can_have_a_subprotocol */, no_master, no_master, "FTP_CONTROL", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 21, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FTP_DATA, 0 /* can_have_a_subprotocol */, no_master, no_master, "FTP_DATA", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 20, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_POP, 0 /* can_have_a_subprotocol */, no_master, no_master, "POP3", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 110, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_POPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "POPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 995, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MAIL_SMTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMTP", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 25, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_SMTPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMTPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 465, 587, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_IMAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMAP", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 143, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_IMAPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMAPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 993, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNS, 1 /* can_have_a_subprotocol */, no_master, no_master, "DNS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 53, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 53, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IPP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IMO, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMO", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 80, 0 /* ntop */, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MDNS, 1 /* can_have_a_subprotocol */, no_master, no_master, "MDNS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5353, 5354, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "NTP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 123, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETBIOS, 0 /* can_have_a_subprotocol */, no_master, no_master, "NetBIOS", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 139, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 137, 138, 139, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NFS, 0 /* can_have_a_subprotocol */, no_master, no_master, "NFS", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 2049, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2049, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSDP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SSDP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BGP, 0 /* can_have_a_subprotocol */, no_master, no_master, "BGP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 179, 2605, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SNMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SNMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 161, 162, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_XDMCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "XDMCP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 177, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 177, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_DANGEROUS, NDPI_PROTOCOL_SMBV1, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMBv1", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SYSLOG, 0 /* can_have_a_subprotocol */, no_master, no_master, "Syslog", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 514, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 514, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "DHCP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 67, 68, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_POSTGRES, 0 /* can_have_a_subprotocol */, no_master, no_master, "PostgreSQL", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 5432, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MYSQL, 0 /* can_have_a_subprotocol */, no_master, no_master, "MySQL", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 3306, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECT_DOWNLOAD_LINK, 0 /* can_have_a_subprotocol */, no_master, no_master, "Direct_Download_Link", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_APPLEJUICE, 0 /* can_have_a_subprotocol */, no_master, no_master, "AppleJuice", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECTCONNECT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DirectConnect", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NATS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Nats", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_NTOP, 0 /* can_have_a_subprotocol */, no_master, no_master, "ntop", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VMWARE, 0 /* can_have_a_subprotocol */, no_master, no_master, "VMware", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 903, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 902, 903, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FBZERO, 0 /* can_have_a_subprotocol */, no_master, no_master, "FacebookZero", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_KONTIKI, 0 /* can_have_a_subprotocol */, no_master, no_master, "Kontiki", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_OPENFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "OpenFT", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_FASTTRACK, 0 /* can_have_a_subprotocol */, no_master, no_master, "FastTrack", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_GNUTELLA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Gnutella", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_EDONKEY, 0 /* can_have_a_subprotocol */, no_master, no_master, "eDonkey", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_BITTORRENT, 0 /* can_have_a_subprotocol */, no_master, no_master, "BitTorrent", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 51413, 53646, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6771, 51413, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Skype", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE_CALL, 0 /* can_have_a_subprotocol */, no_master, no_master, "SkypeCall", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TIKTOK, 0 /* can_have_a_subprotocol */, no_master, no_master, "TikTok", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEREDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Teredo", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3544, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WECHAT, 0 /* can_have_a_subprotocol */, no_master, /* wechat.com */ no_master, "WeChat", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEMCACHED, 0 /* can_have_a_subprotocol */, no_master, no_master, "Memcached", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 11211, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 11211, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMBV23, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMBv23", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MINING, 0 /* can_have_a_subprotocol */, no_master, no_master, "Mining", CUSTOM_CATEGORY_MINING, ndpi_build_default_ports(ports_a, 8333, 30303, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NEST_LOG_SINK, 0 /* can_have_a_subprotocol */, no_master, no_master, "NestLogSink", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 11095, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MODBUS, 1 /* no subprotocol */, no_master, no_master, "Modbus", NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */ ndpi_build_default_ports(ports_a, 502, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_CALL, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppCall", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DATASAVER, 0 /* can_have_a_subprotocol */, no_master, no_master, "DataSaver", NDPI_PROTOCOL_CATEGORY_WEB /* dummy */, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SIGNAL, 0 /* can_have_a_subprotocol */, no_master, /* https://signal.org */ no_master, "Signal", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOH_DOT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DoH_DoT", NDPI_PROTOCOL_CATEGORY_NETWORK /* dummy */, ndpi_build_default_ports(ports_a, 853, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_205, 0 /* can_have_a_subprotocol */, no_master, no_master, "FREE_205", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WIREGUARD, 0 /* can_have_a_subprotocol */, no_master, no_master, "WireGuard", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 51820, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_XBOX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Xbox", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 3074, 3076, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3074, 3076, 500, 3544, 4500) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PLAYSTATION, 0 /* can_have_a_subprotocol */, no_master, no_master, "Playstation", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1935, 3478, 3479, 3480, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3478, 3479, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "QQ", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_RTSP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTSP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 554, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 554, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ICECAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "IceCast", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPLIVE, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPLive", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ZATTOO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Zattoo", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SHOUTCAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "ShoutCast", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOPCAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "Sopcast", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_58, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free58", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVUPLAYER, 0 /* can_have_a_subprotocol */, no_master, no_master, "TVUplayer", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_DOWNLOAD, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Download", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQLIVE, 0 /* can_have_a_subprotocol */, no_master, no_master, "QQLive", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_THUNDER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Thunder", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOULSEEK, 0 /* can_have_a_subprotocol */, no_master, no_master, "Soulseek", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PS_VUE, 0 /* can_have_a_subprotocol */, no_master, no_master, "PS_VUE", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_IRC, 0 /* can_have_a_subprotocol */, no_master, no_master, "IRC", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 194, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 194, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AYIYA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Ayiya", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5072, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UNENCRYPTED_JABBER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Unencrypted_Jabber", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FREE_69, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free69", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_71, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free71", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_VRRP, 0 /* can_have_a_subprotocol */, no_master, no_master, "VRRP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STEAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Steam", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HALFLIFE2, 0 /* can_have_a_subprotocol */, no_master, no_master, "HalfLife2", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLDOFWARCRAFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "WorldOfWarcraft", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_HOTSPOT_SHIELD, 0 /* can_have_a_subprotocol */, no_master, no_master, "HotspotShield", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_TELNET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Telnet", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 23, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); custom_master[0] = NDPI_PROTOCOL_SIP, custom_master[1] = NDPI_PROTOCOL_H323; ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_STUN, 0 /* can_have_a_subprotocol */, no_master, custom_master, "STUN", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3478, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_IP_IPSEC, 0 /* can_have_a_subprotocol */, no_master, no_master, "IPsec", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 500, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 500, 4500, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_GRE, 0 /* can_have_a_subprotocol */, no_master, no_master, "GRE", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "ICMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IGMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IGMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_EGP, 0 /* can_have_a_subprotocol */, no_master, no_master, "EGP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_SCTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SCTP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_OSPF, 0 /* can_have_a_subprotocol */, no_master, no_master, "OSPF", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 2604, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IP_IN_IP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IP_in_IP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RDP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RDP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 3389, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3389, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VNC, 0 /* can_have_a_subprotocol */, no_master, no_master, "VNC", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FREE90, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free90", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZOOM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Zoom", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_FILES, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppFiles", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsApp", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_TLS, 1 /* can_have_a_subprotocol */, no_master, no_master, "TLS", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSH, 0 /* can_have_a_subprotocol */, no_master, no_master, "SSH", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 22, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_USENET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Usenet", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MGCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "MGCP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IAX, 0 /* can_have_a_subprotocol */, no_master, no_master, "IAX", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 4569, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 4569, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AFP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AFP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 548, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 548, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HULU, 0 /* can_have_a_subprotocol */, no_master, no_master, "Hulu", NDPI_PROTOCOL_CATEGORY_STREAMING, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CHECKMK, 0 /* can_have_a_subprotocol */, no_master, no_master, "CHECKMK", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 6556, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_STEALTHNET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Stealthnet", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_AIMINI, 0 /* can_have_a_subprotocol */, no_master, no_master, "Aimini", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SIP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SIP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 5060, 5061, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5060, 5061, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TRUPHONE, 0 /* can_have_a_subprotocol */, no_master, no_master, "TruPhone", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMPV6, 0 /* can_have_a_subprotocol */, no_master, no_master, "ICMPV6", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCPV6, 0 /* can_have_a_subprotocol */, no_master, no_master, "DHCPV6", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ARMAGETRON, 0 /* can_have_a_subprotocol */, no_master, no_master, "Armagetron", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CROSSFIRE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Crossfire", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOFUS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Dofus", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FIESTA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Fiesta", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FLORENSIA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Florensia", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_GUILDWARS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Guildwars", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_ACTIVESYNC, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_ActiveSync", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KERBEROS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Kerberos", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 88, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 88, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LDAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "LDAP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 389, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 389, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MAPLESTORY, 0 /* can_have_a_subprotocol */, no_master, no_master, "MapleStory", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MSSQL_TDS, 0 /* can_have_a_subprotocol */, no_master, no_master, "MsSQL-TDS", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1433, 1434, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PPTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPTP", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WARCRAFT3, 0 /* can_have_a_subprotocol */, no_master, no_master, "Warcraft3", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLD_OF_KUNG_FU, 0 /* can_have_a_subprotocol */, no_master, no_master, "WorldOfKungFu", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DCERPC, 0 /* can_have_a_subprotocol */, no_master, no_master, "DCE_RPC", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 135, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETFLOW, 0 /* can_have_a_subprotocol */, no_master, no_master, "NetFlow", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2055, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SFLOW, 0 /* can_have_a_subprotocol */, no_master, no_master, "sFlow", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6343, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_CONNECT, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Connect", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_PROXY, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Proxy", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8080, 3128, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CITRIX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Citrix", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1494, 2598, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBEX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Webex", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RADIUS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Radius", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1812, 1813, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1812, 1813, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMVIEWER, 0 /* can_have_a_subprotocol */, no_master, no_master, "TeamViewer", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5938, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5938, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LOTUS_NOTES, 0 /* can_have_a_subprotocol */, no_master, no_master, "LotusNotes", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 1352, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SAP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3201, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_GTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "GTP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2152, 2123, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UPNP, 0 /* can_have_a_subprotocol */, no_master, no_master, "UPnP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1780, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1900, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TELEGRAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Telegram", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_QUIC, 1 /* can_have_a_subprotocol */, no_master, no_master, "QUIC", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 443, 80, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DIAMETER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Diameter", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3868, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_APPLE_PUSH, 0 /* can_have_a_subprotocol */, no_master, no_master, "ApplePush", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DROPBOX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Dropbox", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 17500, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SPOTIFY, 0 /* can_have_a_subprotocol */, no_master, no_master, "Spotify", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MESSENGER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Messenger", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LISP, 0 /* can_have_a_subprotocol */, no_master, no_master, "LISP", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 4342, 4341, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_EAQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "EAQ", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6000, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KAKAOTALK_VOICE, 0 /* can_have_a_subprotocol */, no_master, no_master, "KakaoTalk_Voice", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MPEGTS, 0 /* can_have_a_subprotocol */, no_master, no_master, "MPEG_TS", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); /* http://en.wikipedia.org/wiki/Link-local_Multicast_Name_Resolution */ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LLMNR, 0 /* can_have_a_subprotocol */, no_master, no_master, "LLMNR", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5355, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5355, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_REMOTE_SCAN, 0 /* can_have_a_subprotocol */, no_master, no_master, "RemoteScan", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 6077, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6078, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_H323, 0 /* can_have_a_subprotocol */, no_master, no_master, "H323", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 1719, 1720, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1719, 1720, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OPENVPN, 0 /* can_have_a_subprotocol */, no_master, no_master, "OpenVPN", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 1194, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1194, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NOE, 0 /* can_have_a_subprotocol */, no_master, no_master, "NOE", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CISCOVPN, 0 /* can_have_a_subprotocol */, no_master, no_master, "CiscoVPN", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 10000, 8008, 8009, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 10000, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMSPEAK, 0 /* can_have_a_subprotocol */, no_master, no_master, "TeamSpeak", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKINNY, 0 /* can_have_a_subprotocol */, no_master, no_master, "CiscoSkinny", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 2000, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTCP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RSYNC, 0 /* can_have_a_subprotocol */, no_master, no_master, "RSYNC", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 873, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ORACLE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Oracle", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1521, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CORBA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Corba", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UBUNTUONE, 0 /* can_have_a_subprotocol */, no_master, no_master, "UbuntuONE", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHOIS_DAS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Whois-DAS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 43, 4343, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_COLLECTD, 0 /* can_have_a_subprotocol */, no_master, no_master, "Collectd", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 25826, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOCKS, 0 /* can_have_a_subprotocol */, no_master, no_master, "SOCKS", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 1080, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 1080, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TFTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "TFTP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 69, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTMP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 1935, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PANDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Pando_Media_Booster", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEGACO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Megaco", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 2944, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_REDIS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Redis", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 6379, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZMQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "ZeroMQ", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_VHUA, 0 /* can_have_a_subprotocol */, no_master, no_master, "VHUA", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 58267, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STARCRAFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "Starcraft", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1119, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 1119, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_UBNTAC2, 0 /* can_have_a_subprotocol */, no_master, no_master, "UBNTAC2", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 10001, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VIBER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Viber", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 7985, 5242, 5243, 4244, 0), /* TCP */ ndpi_build_default_ports(ports_b, 7985, 7987, 5242, 5243, 4244)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_COAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "COAP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 5683, 5684, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MQTT, 0 /* can_have_a_subprotocol */, no_master, no_master, "MQTT", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 1883, 8883, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOMEIP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SOMEIP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 30491, 30501, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 30491, 30501, 30490, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RX, 0 /* can_have_a_subprotocol */, no_master, no_master, "RX", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_GIT, 0 /* can_have_a_subprotocol */, no_master, no_master, "Git", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 9418, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DRDA, 0 /* can_have_a_subprotocol */, no_master, no_master, "DRDA", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HANGOUT_DUO, 0 /* can_have_a_subprotocol */, no_master, no_master, "GoogleHangoutDuo", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BJNP, 0 /* can_have_a_subprotocol */, no_master, no_master, "BJNP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 8612, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMPP", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_OOKLA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Ookla", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMQP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AMQP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_DNSCRYPT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DNScrypt", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TINC, 0 /* can_have_a_subprotocol */, no_master, no_master, "TINC", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 655, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 655, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FIX, 0 /* can_have_a_subprotocol */, no_master, no_master, "FIX", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_NINTENDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Nintendo", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CSGO, 0 /* can_have_a_subprotocol */, no_master, no_master, "CSGO", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AJP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AJP", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8009, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TARGUS_GETDATA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Targus Dataspeed", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5001, 5201, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5001, 5201, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMAZON_VIDEO, 0 /* can_have_a_subprotocol */, no_master, no_master, "AmazonVideo", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNP3, 1 /* no subprotocol */, no_master, no_master, "DNP3", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 20000, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IEC60870, 1 /* no subprotocol */, no_master, no_master, "IEC60870", NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */ ndpi_build_default_ports(ports_a, 2404, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BLOOMBERG, 1 /* no subprotocol */, no_master, no_master, "Bloomberg", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CAPWAP, 1 /* no subprotocol */, no_master, no_master, "CAPWAP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5246, 5247, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZABBIX, 1 /* no subprotocol */, no_master, no_master, "Zabbix", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 10050, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_S7COMM, 1 /* no subprotocol */, no_master, no_master, "s7comm", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 102, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MSTEAMS, 1 /* no subprotocol */, no_master, no_master, "Teams", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBSOCKET, 1 /* can_have_a_subprotocol */, no_master, no_master, "WebSocket", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ANYDESK, 1 /* no subprotocol */, no_master, no_master, "AnyDesk", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_main.c" #endif /* calling function for host and content matched protocols */ init_string_based_protocols(ndpi_str); ndpi_validate_protocol_initialization(ndpi_str); } /* ****************************************************** */ #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_protocols.c" #endif /* ****************************************************** */ static int ac_match_handler(AC_MATCH_t *m, AC_TEXT_t *txt, AC_REP_t *match) { int min_len = (txt->length < m->patterns->length) ? txt->length : m->patterns->length; char buf[64] = {'\0'}, *whatfound; int min_buf_len = (txt->length > 63 /* sizeof(buf)-1 */) ? 63 : txt->length; u_int buf_len = strlen(buf); strncpy(buf, txt->astring, min_buf_len); buf[min_buf_len] = '\0'; #ifdef MATCH_DEBUG printf("Searching [to search: %s/%u][pattern: %s/%u] [len: %d][match_num: %u][%s]\n", buf, (unigned int) txt->length, m->patterns->astring, (unigned int) m->patterns->length, min_len, m->match_num, m->patterns->astring); #endif whatfound = strstr(buf, m->patterns->astring); #ifdef MATCH_DEBUG printf("[NDPI] %s() [searching=%s][pattern=%s][%s][%c]\n", __FUNCTION__, buf, m->patterns->astring, whatfound ? whatfound : "<NULL>", whatfound[-1]); #endif if(whatfound) { /* The patch below allows in case of pattern ws.amazon.com to avoid matching aws.amazon.com whereas a.ws.amazon.com has to match */ if((whatfound != buf) && (m->patterns->astring[0] != '.') /* The searched pattern does not start with . */ && strchr(m->patterns->astring, '.') /* The matched pattern has a . (e.g. numeric or sym IPs) */) { int len = strlen(m->patterns->astring); if((whatfound[-1] != '.') || ((m->patterns->astring[len - 1] != '.') && (whatfound[len] != '\0') /* endsWith does not hold here */)) { return(0); } else { memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t)); /* Partial match? */ return(0); /* Keep searching as probably there is a better match */ } } } /* Return 1 for stopping to the first match. We might consider searching for the more specific match, paying more cpu cycles. */ memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t)); if(((buf_len >= min_len) && (strncmp(&buf[buf_len - min_len], m->patterns->astring, min_len) == 0)) || (strncmp(buf, m->patterns->astring, min_len) == 0) /* begins with */ ) { #ifdef MATCH_DEBUG printf("Found match [%s][%s] [len: %d]" // "[proto_id: %u]" "\n", buf, m->patterns->astring, min_len /* , *matching_protocol_id */); #endif return(1); /* If the pattern found matches the string at the beginning we stop here */ } else { #ifdef MATCH_DEBUG printf("NO match found: continue\n"); #endif return(0); /* 0 to continue searching, !0 to stop */ } } /* ******************************************************************** */ static int fill_prefix_v4(prefix_t *p, const struct in_addr *a, int b, int mb) { if(b < 0 || b > mb) return(-1); memset(p, 0, sizeof(prefix_t)); memcpy(&p->add.sin, a, (mb + 7) / 8); p->family = AF_INET; p->bitlen = b; p->ref_count = 0; return(0); } /* ******************************************* */ static int fill_prefix_v6(prefix_t *prefix, const struct in6_addr *addr, int bits, int maxbits) { #ifdef PATRICIA_IPV6 if(bits < 0 || bits > maxbits) return -1; memcpy(&prefix->add.sin6, addr, (maxbits + 7) / 8); prefix->family = AF_INET6, prefix->bitlen = bits, prefix->ref_count = 0; return 0; #else return(-1); #endif } /* ******************************************* */ u_int16_t ndpi_network_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin /* network byte order */) { prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix); return(node ? node->value.uv.user_value : NDPI_PROTOCOL_UNKNOWN); } /* ******************************************* */ u_int16_t ndpi_network_port_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin /* network byte order */, u_int16_t port /* network byte order */) { prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix); if(node) { if((node->value.uv.additional_user_value == 0) || (node->value.uv.additional_user_value == port)) return(node->value.uv.user_value); } return(NDPI_PROTOCOL_UNKNOWN); } /* ******************************************* */ #if 0 static u_int8_t tor_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin) { return((ndpi_network_ptree_match(ndpi_str, pin) == NDPI_PROTOCOL_TOR) ? 1 : 0); } #endif /* ******************************************* */ u_int8_t ndpi_is_tor_flow(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; if(packet->tcp != NULL) { if(packet->iph) { if(flow->guessed_host_protocol_id == NDPI_PROTOCOL_TOR) return(1); } } return(0); } /* ******************************************* */ static patricia_node_t *add_to_ptree(patricia_tree_t *tree, int family, void *addr, int bits) { prefix_t prefix; patricia_node_t *node; fill_prefix_v4(&prefix, (struct in_addr *) addr, bits, tree->maxbits); node = ndpi_patricia_lookup(tree, &prefix); if(node) memset(&node->value, 0, sizeof(node->value)); return(node); } /* ******************************************* */ /* Load a file containing IPv4 addresses in CIDR format as 'protocol_id' Return: the number of entries loaded or -1 in case of error */ int ndpi_load_ipv4_ptree(struct ndpi_detection_module_struct *ndpi_str, const char *path, u_int16_t protocol_id) { char buffer[128], *line, *addr, *cidr, *saveptr; FILE *fd; int len; u_int num_loaded = 0; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); return(-1); } while (1) { line = fgets(buffer, sizeof(buffer), fd); if(line == NULL) break; len = strlen(line); if((len <= 1) || (line[0] == '#')) continue; line[len - 1] = '\0'; addr = strtok_r(line, "/", &saveptr); if(addr) { struct in_addr pin; patricia_node_t *node; cidr = strtok_r(NULL, "\n", &saveptr); pin.s_addr = inet_addr(addr); if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, cidr ? atoi(cidr) : 32 /* bits */)) != NULL) { node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = 0 /* port */; num_loaded++; } } } fclose(fd); return(num_loaded); } /* ******************************************* */ static void ndpi_init_ptree_ipv4(struct ndpi_detection_module_struct *ndpi_str, void *ptree, ndpi_network host_list[], u_int8_t skip_tor_hosts) { int i; for (i = 0; host_list[i].network != 0x0; i++) { struct in_addr pin; patricia_node_t *node; if(skip_tor_hosts && (host_list[i].value == NDPI_PROTOCOL_TOR)) continue; pin.s_addr = htonl(host_list[i].network); if((node = add_to_ptree(ptree, AF_INET, &pin, host_list[i].cidr /* bits */)) != NULL) { node->value.uv.user_value = host_list[i].value, node->value.uv.additional_user_value = 0; } } } /* ******************************************* */ static int ndpi_add_host_ip_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, u_int16_t protocol_id) { patricia_node_t *node; struct in_addr pin; int bits = 32; char *ptr = strrchr(value, '/'); u_int16_t port = 0; /* Format ip:8.248.73.247:443 */ char *double_column; if(ptr) { ptr[0] = '\0'; ptr++; if((double_column = strrchr(ptr, ':')) != NULL) { double_column[0] = '\0'; port = atoi(&double_column[1]); } if(atoi(ptr) >= 0 && atoi(ptr) <= 32) bits = atoi(ptr); } else { /* Let's check if there is the port defined Example: ip:8.248.73.247:443@AmazonPrime */ double_column = strrchr(value, ':'); if(double_column) { double_column[0] = '\0'; port = atoi(&double_column[1]); } } inet_pton(AF_INET, value, &pin); if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, bits)) != NULL) { node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = htons(port); } return(0); } void set_ndpi_malloc(void *(*__ndpi_malloc)(size_t size)) { _ndpi_malloc = __ndpi_malloc; } void set_ndpi_flow_malloc(void *(*__ndpi_flow_malloc)(size_t size)) { _ndpi_flow_malloc = __ndpi_flow_malloc; } void set_ndpi_free(void (*__ndpi_free)(void *ptr)) { _ndpi_free = __ndpi_free; } void set_ndpi_flow_free(void (*__ndpi_flow_free)(void *ptr)) { _ndpi_flow_free = __ndpi_flow_free; } void ndpi_debug_printf(unsigned int proto, struct ndpi_detection_module_struct *ndpi_str, ndpi_log_level_t log_level, const char *file_name, const char *func_name, int line_number, const char *format, ...) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES va_list args; #define MAX_STR_LEN 250 char str[MAX_STR_LEN]; if(ndpi_str != NULL && log_level > NDPI_LOG_ERROR && proto > 0 && proto < NDPI_MAX_SUPPORTED_PROTOCOLS && !NDPI_ISSET(&ndpi_str->debug_bitmask, proto)) return; va_start(args, format); vsnprintf(str, sizeof(str) - 1, format, args); va_end(args); if(ndpi_str != NULL) { printf("%s:%s:%-3d - [%s]: %s", file_name, func_name, line_number, ndpi_get_proto_name(ndpi_str, proto), str); } else { printf("Proto: %u, %s", proto, str); } #endif } void set_ndpi_debug_function(struct ndpi_detection_module_struct *ndpi_str, ndpi_debug_function_ptr ndpi_debug_printf) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES ndpi_str->ndpi_debug_printf = ndpi_debug_printf; #endif } /* ****************************************** */ /* Keep it in order and in sync with ndpi_protocol_category_t in ndpi_typedefs.h */ static const char *categories[] = { "Unspecified", "Media", "VPN", "Email", "DataTransfer", "Web", "SocialNetwork", "Download-FileTransfer-FileSharing", "Game", "Chat", "VoIP", "Database", "RemoteAccess", "Cloud", "Network", "Collaborative", "RPC", "Streaming", "System", "SoftwareUpdate", "", "", "", "", "", "Music", "Video", "Shopping", "Productivity", "FileSharing", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Mining", /* 99 */ "Malware", "Advertisement", "Banned_Site", "Site_Unavailable", "Allowed_Site", "Antimalware", }; /* ******************************************************************** */ struct ndpi_detection_module_struct *ndpi_init_detection_module(ndpi_init_prefs prefs) { struct ndpi_detection_module_struct *ndpi_str = ndpi_malloc(sizeof(struct ndpi_detection_module_struct)); int i; if(ndpi_str == NULL) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES NDPI_LOG_ERR(ndpi_str, "ndpi_init_detection_module initial malloc failed for ndpi_str\n"); #endif /* NDPI_ENABLE_DEBUG_MESSAGES */ return(NULL); } memset(ndpi_str, 0, sizeof(struct ndpi_detection_module_struct)); #ifdef NDPI_ENABLE_DEBUG_MESSAGES set_ndpi_debug_function(ndpi_str, (ndpi_debug_function_ptr) ndpi_debug_printf); #endif /* NDPI_ENABLE_DEBUG_MESSAGES */ if((ndpi_str->protocols_ptree = ndpi_New_Patricia(32 /* IPv4 */)) != NULL) ndpi_init_ptree_ipv4(ndpi_str, ndpi_str->protocols_ptree, host_protocol_list, prefs & ndpi_dont_load_tor_hosts); NDPI_BITMASK_RESET(ndpi_str->detection_bitmask); #ifdef NDPI_ENABLE_DEBUG_MESSAGES ndpi_str->user_data = NULL; #endif ndpi_str->ticks_per_second = 1000; /* ndpi_str->ticks_per_second */ ndpi_str->tcp_max_retransmission_window_size = NDPI_DEFAULT_MAX_TCP_RETRANSMISSION_WINDOW_SIZE; ndpi_str->directconnect_connection_ip_tick_timeout = NDPI_DIRECTCONNECT_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->rtsp_connection_timeout = NDPI_RTSP_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->irc_timeout = NDPI_IRC_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->gnutella_timeout = NDPI_GNUTELLA_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->thunder_timeout = NDPI_THUNDER_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->zattoo_connection_timeout = NDPI_ZATTOO_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->jabber_stun_timeout = NDPI_JABBER_STUN_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->jabber_file_transfer_timeout = NDPI_JABBER_FT_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->soulseek_connection_ip_tick_timeout = NDPI_SOULSEEK_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->ndpi_num_supported_protocols = NDPI_MAX_SUPPORTED_PROTOCOLS; ndpi_str->ndpi_num_custom_protocols = 0; ndpi_str->host_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->content_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->bigrams_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->impossible_bigrams_automa.ac_automa = ac_automata_init(ac_match_handler); if((sizeof(categories) / sizeof(char *)) != NDPI_PROTOCOL_NUM_CATEGORIES) { NDPI_LOG_ERR(ndpi_str, "[NDPI] invalid categories length: expected %u, got %u\n", NDPI_PROTOCOL_NUM_CATEGORIES, (unsigned int) (sizeof(categories) / sizeof(char *))); return(NULL); } ndpi_str->custom_categories.hostnames.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->custom_categories.ipAddresses = ndpi_New_Patricia(32 /* IPv4 */); ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */); if((ndpi_str->custom_categories.ipAddresses == NULL) || (ndpi_str->custom_categories.ipAddresses_shadow == NULL)) return(NULL); ndpi_init_protocol_defaults(ndpi_str); for (i = 0; i < NUM_CUSTOM_CATEGORIES; i++) snprintf(ndpi_str->custom_category_labels[i], CUSTOM_CATEGORY_LABEL_LEN, "User custom category %u", (unsigned int) (i + 1)); return(ndpi_str); } /* *********************************************** */ void ndpi_finalize_initalization(struct ndpi_detection_module_struct *ndpi_str) { u_int i; for (i = 0; i < 4; i++) { ndpi_automa *automa; switch (i) { case 0: automa = &ndpi_str->host_automa; break; case 1: automa = &ndpi_str->content_automa; break; case 2: automa = &ndpi_str->bigrams_automa; break; case 3: automa = &ndpi_str->impossible_bigrams_automa; break; default: automa = NULL; break; } if(automa) { ac_automata_finalize((AC_AUTOMATA_t *) automa->ac_automa); automa->ac_automa_finalized = 1; } } } /* *********************************************** */ /* Wrappers */ void *ndpi_init_automa(void) { return(ac_automata_init(ac_match_handler)); } /* ****************************************************** */ int ndpi_add_string_value_to_automa(void *_automa, char *str, u_int32_t num) { AC_PATTERN_t ac_pattern; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_ERROR_t rc; if(automa == NULL) return(-1); memset(&ac_pattern, 0, sizeof(ac_pattern)); ac_pattern.astring = str; ac_pattern.rep.number = num; ac_pattern.length = strlen(ac_pattern.astring); rc = ac_automata_add(automa, &ac_pattern); return(rc == ACERR_SUCCESS || rc == ACERR_DUPLICATE_PATTERN ? 0 : -1); } /* ****************************************************** */ int ndpi_add_string_to_automa(void *_automa, char *str) { return(ndpi_add_string_value_to_automa(_automa, str, 1)); } /* ****************************************************** */ void ndpi_free_automa(void *_automa) { ac_automata_release((AC_AUTOMATA_t *) _automa, 0); } /* ****************************************************** */ void ndpi_finalize_automa(void *_automa) { ac_automata_finalize((AC_AUTOMATA_t *) _automa); } /* ****************************************************** */ int ndpi_match_string(void *_automa, char *string_to_match) { AC_REP_t match = { NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; int rc; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = strlen(string_to_match); rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; return(rc ? match.number : 0); } /* ****************************************************** */ int ndpi_match_string_protocol_id(void *_automa, char *string_to_match, u_int match_len, u_int16_t *protocol_id, ndpi_protocol_category_t *category, ndpi_protocol_breed_t *breed) { AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; int rc; *protocol_id = (u_int16_t)-1; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = match_len; rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; if(rc) *protocol_id = (u_int16_t)match.number, *category = match.category, *breed = match.breed; else *protocol_id = NDPI_PROTOCOL_UNKNOWN; return((*protocol_id != NDPI_PROTOCOL_UNKNOWN) ? 0 : -1); } /* ****************************************************** */ int ndpi_match_string_value(void *_automa, char *string_to_match, u_int match_len, u_int32_t *num) { AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; int rc; *num = (u_int32_t)-1; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = match_len; rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; if(rc) *num = match.number; else *num = 0; return(rc ? 0 : -1); } /* *********************************************** */ int ndpi_match_custom_category(struct ndpi_detection_module_struct *ndpi_str, char *name, u_int name_len, ndpi_protocol_category_t *category) { ndpi_protocol_breed_t breed; u_int16_t id; int rc = ndpi_match_string_protocol_id(ndpi_str->custom_categories.hostnames.ac_automa, name, name_len, &id, category, &breed); return(rc); } /* *********************************************** */ int ndpi_get_custom_category_match(struct ndpi_detection_module_struct *ndpi_str, char *name_or_ip, u_int name_len, ndpi_protocol_category_t *id) { char ipbuf[64], *ptr; struct in_addr pin; u_int cp_len = ndpi_min(sizeof(ipbuf) - 1, name_len); if(!ndpi_str->custom_categories.categories_loaded) return(-1); if(cp_len > 0) { memcpy(ipbuf, name_or_ip, cp_len); ipbuf[cp_len] = '\0'; } else ipbuf[0] = '\0'; ptr = strrchr(ipbuf, '/'); if(ptr) ptr[0] = '\0'; if(inet_pton(AF_INET, ipbuf, &pin) == 1) { /* Search IP */ prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, &pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); if(node) { *id = node->value.uv.user_value; return(0); } return(-1); } else { /* Search Host */ return(ndpi_match_custom_category(ndpi_str, name_or_ip, name_len, id)); } } /* *********************************************** */ static void free_ptree_data(void *data) { ; } /* ****************************************************** */ void ndpi_exit_detection_module(struct ndpi_detection_module_struct *ndpi_str) { if(ndpi_str != NULL) { int i; for (i = 0; i < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS); i++) { if(ndpi_str->proto_defaults[i].protoName) ndpi_free(ndpi_str->proto_defaults[i].protoName); } /* NDPI_PROTOCOL_TINC */ if(ndpi_str->tinc_cache) cache_free((cache_t)(ndpi_str->tinc_cache)); if(ndpi_str->ookla_cache) ndpi_lru_free_cache(ndpi_str->ookla_cache); if(ndpi_str->stun_cache) ndpi_lru_free_cache(ndpi_str->stun_cache); if(ndpi_str->msteams_cache) ndpi_lru_free_cache(ndpi_str->msteams_cache); if(ndpi_str->protocols_ptree) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->protocols_ptree, free_ptree_data); if(ndpi_str->udpRoot != NULL) ndpi_tdestroy(ndpi_str->udpRoot, ndpi_free); if(ndpi_str->tcpRoot != NULL) ndpi_tdestroy(ndpi_str->tcpRoot, ndpi_free); if(ndpi_str->host_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->host_automa.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->content_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->content_automa.ac_automa, 0); if(ndpi_str->bigrams_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->bigrams_automa.ac_automa, 0); if(ndpi_str->impossible_bigrams_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->impossible_bigrams_automa.ac_automa, 0); if(ndpi_str->custom_categories.hostnames.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->custom_categories.hostnames_shadow.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->custom_categories.ipAddresses != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data); if(ndpi_str->custom_categories.ipAddresses_shadow != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses_shadow, free_ptree_data); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/ndpi_exit_detection_module.c" #endif ndpi_free(ndpi_str); } } /* ****************************************************** */ int ndpi_get_protocol_id_master_proto(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protocol_id, u_int16_t **tcp_master_proto, u_int16_t **udp_master_proto) { if(protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) { *tcp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_tcp_protoId, *udp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_udp_protoId; return(-1); } *tcp_master_proto = ndpi_str->proto_defaults[protocol_id].master_tcp_protoId, *udp_master_proto = ndpi_str->proto_defaults[protocol_id].master_udp_protoId; return(0); } /* ****************************************************** */ static ndpi_default_ports_tree_node_t *ndpi_get_guessed_protocol_id(struct ndpi_detection_module_struct *ndpi_str, u_int8_t proto, u_int16_t sport, u_int16_t dport) { ndpi_default_ports_tree_node_t node; if(sport && dport) { int low = ndpi_min(sport, dport); int high = ndpi_max(sport, dport); const void *ret; node.default_port = low; /* Check server port first */ ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot, ndpi_default_ports_tree_node_t_cmp); if(ret == NULL) { node.default_port = high; ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot, ndpi_default_ports_tree_node_t_cmp); } if(ret) return(*(ndpi_default_ports_tree_node_t **) ret); } return(NULL); } /* ****************************************************** */ /* These are UDP protocols that must fit a single packet and thus that if have NOT been detected they cannot be guessed as they have been excluded */ u_int8_t is_udp_guessable_protocol(u_int16_t l7_guessed_proto) { switch (l7_guessed_proto) { case NDPI_PROTOCOL_QUIC: case NDPI_PROTOCOL_SNMP: case NDPI_PROTOCOL_NETFLOW: /* TODO: add more protocols (if any missing) */ return(1); } return(0); } /* ****************************************************** */ u_int16_t ndpi_guess_protocol_id(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t proto, u_int16_t sport, u_int16_t dport, u_int8_t *user_defined_proto) { *user_defined_proto = 0; /* Default */ if(sport && dport) { ndpi_default_ports_tree_node_t *found = ndpi_get_guessed_protocol_id(ndpi_str, proto, sport, dport); if(found != NULL) { u_int16_t guessed_proto = found->proto->protoId; /* We need to check if the guessed protocol isn't excluded by nDPI */ if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, guessed_proto) && is_udp_guessable_protocol(guessed_proto)) return(NDPI_PROTOCOL_UNKNOWN); else { *user_defined_proto = found->customUserProto; return(guessed_proto); } } } else { /* No TCP/UDP */ switch (proto) { case NDPI_IPSEC_PROTOCOL_ESP: case NDPI_IPSEC_PROTOCOL_AH: return(NDPI_PROTOCOL_IP_IPSEC); break; case NDPI_GRE_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_GRE); break; case NDPI_ICMP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_ICMP); break; case NDPI_IGMP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_IGMP); break; case NDPI_EGP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_EGP); break; case NDPI_SCTP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_SCTP); break; case NDPI_OSPF_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_OSPF); break; case NDPI_IPIP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_IP_IN_IP); break; case NDPI_ICMPV6_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_ICMPV6); break; case 112: return(NDPI_PROTOCOL_IP_VRRP); break; } } return(NDPI_PROTOCOL_UNKNOWN); } /* ******************************************************************** */ u_int ndpi_get_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_supported_protocols); } /* ******************************************************************** */ #ifdef WIN32 char *strsep(char **sp, char *sep) { char *p, *s; if(sp == NULL || *sp == NULL || **sp == '\0') return(NULL); s = *sp; p = s + strcspn(s, sep); if(*p != '\0') *p++ = '\0'; *sp = p; return(s); } #endif /* ******************************************************************** */ int ndpi_handle_rule(struct ndpi_detection_module_struct *ndpi_str, char *rule, u_int8_t do_add) { char *at, *proto, *elem; ndpi_proto_defaults_t *def; u_int16_t subprotocol_id, i; at = strrchr(rule, '@'); if(at == NULL) { NDPI_LOG_ERR(ndpi_str, "Invalid rule '%s'\n", rule); return(-1); } else at[0] = 0, proto = &at[1]; for (i = 0; proto[i] != '\0'; i++) { switch (proto[i]) { case '/': case '&': case '^': case ':': case ';': case '\'': case '"': case ' ': proto[i] = '_'; break; } } for (i = 0, def = NULL; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) { if(ndpi_str->proto_defaults[i].protoName && strcasecmp(ndpi_str->proto_defaults[i].protoName, proto) == 0) { def = &ndpi_str->proto_defaults[i]; subprotocol_id = i; break; } } if(def == NULL) { if(!do_add) { /* We need to remove a rule */ NDPI_LOG_ERR(ndpi_str, "Unable to find protocol '%s': skipping rule '%s'\n", proto, rule); return(-3); } else { ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}; if(ndpi_str->ndpi_num_custom_protocols >= (NDPI_MAX_NUM_CUSTOM_PROTOCOLS - 1)) { NDPI_LOG_ERR(ndpi_str, "Too many protocols defined (%u): skipping protocol %s\n", ndpi_str->ndpi_num_custom_protocols, proto); return(-2); } ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, ndpi_str->ndpi_num_supported_protocols, 0 /* can_have_a_subprotocol */, no_master, no_master, proto, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, /* TODO add protocol category support in rules */ ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); def = &ndpi_str->proto_defaults[ndpi_str->ndpi_num_supported_protocols]; subprotocol_id = ndpi_str->ndpi_num_supported_protocols; ndpi_str->ndpi_num_supported_protocols++, ndpi_str->ndpi_num_custom_protocols++; } } while ((elem = strsep(&rule, ",")) != NULL) { char *attr = elem, *value = NULL; ndpi_port_range range; int is_tcp = 0, is_udp = 0, is_ip = 0; if(strncmp(attr, "tcp:", 4) == 0) is_tcp = 1, value = &attr[4]; else if(strncmp(attr, "udp:", 4) == 0) is_udp = 1, value = &attr[4]; else if(strncmp(attr, "ip:", 3) == 0) is_ip = 1, value = &attr[3]; else if(strncmp(attr, "host:", 5) == 0) { /* host:"<value>",host:"<value>",.....@<subproto> */ value = &attr[5]; if(value[0] == '"') value++; /* remove leading " */ if(value[strlen(value) - 1] == '"') value[strlen(value) - 1] = '\0'; /* remove trailing " */ } if(is_tcp || is_udp) { u_int p_low, p_high; if(sscanf(value, "%u-%u", &p_low, &p_high) == 2) range.port_low = p_low, range.port_high = p_high; else range.port_low = range.port_high = atoi(&elem[4]); if(do_add) addDefaultPort(ndpi_str, &range, def, 1 /* Custom user proto */, is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot, __FUNCTION__, __LINE__); else removeDefaultPort(&range, def, is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot); } else if(is_ip) { /* NDPI_PROTOCOL_TOR */ ndpi_add_host_ip_subprotocol(ndpi_str, value, subprotocol_id); } else { if(do_add) ndpi_add_host_url_subprotocol(ndpi_str, value, subprotocol_id, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_ACCEPTABLE); else ndpi_remove_host_url_subprotocol(ndpi_str, value, subprotocol_id); } } return(0); } /* ******************************************************************** */ /* * Format: * * <host|ip> <category_id> * * Notes: * - host and category are separated by a single TAB * - empty lines or lines starting with # are ignored */ int ndpi_load_categories_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) { char buffer[512], *line, *name, *category, *saveptr; FILE *fd; int len, num = 0; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); return(-1); } while (1) { line = fgets(buffer, sizeof(buffer), fd); if(line == NULL) break; len = strlen(line); if((len <= 1) || (line[0] == '#')) continue; line[len - 1] = '\0'; name = strtok_r(line, "\t", &saveptr); if(name) { category = strtok_r(NULL, "\t", &saveptr); if(category) { int rc = ndpi_load_category(ndpi_str, name, (ndpi_protocol_category_t) atoi(category)); if(rc >= 0) num++; } } } fclose(fd); ndpi_enable_loaded_categories(ndpi_str); return(num); } /* ******************************************************************** */ /* Format: <tcp|udp>:<port>,<tcp|udp>:<port>,.....@<proto> Subprotocols Format: host:"<value>",host:"<value>",.....@<subproto> IP based Subprotocols Format (<value> is IP or CIDR): ip:<value>,ip:<value>,.....@<subproto> Example: tcp:80,tcp:3128@HTTP udp:139@NETBIOS */ int ndpi_load_protocols_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) { FILE *fd; char *buffer, *old_buffer; int chunk_len = 512, buffer_len = chunk_len, old_buffer_len; int i, rc = -1; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); goto error; } buffer = ndpi_malloc(buffer_len); if(buffer == NULL) { NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n"); goto close_fd; } while (1) { char *line = buffer; int line_len = buffer_len; while ((line = fgets(line, line_len, fd)) != NULL && line[strlen(line) - 1] != '\n') { i = strlen(line); old_buffer = buffer; old_buffer_len = buffer_len; buffer_len += chunk_len; buffer = ndpi_realloc(old_buffer, old_buffer_len, buffer_len); if(buffer == NULL) { NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n"); ndpi_free(old_buffer); goto close_fd; } line = &buffer[i]; line_len = chunk_len; } if(!line) /* safety check */ break; i = strlen(buffer); if((i <= 1) || (buffer[0] == '#')) continue; else buffer[i - 1] = '\0'; ndpi_handle_rule(ndpi_str, buffer, 1); } rc = 0; ndpi_free(buffer); close_fd: fclose(fd); error: return(rc); } /* ******************************************************************** */ /* ntop */ void ndpi_set_bitmask_protocol_detection(char *label, struct ndpi_detection_module_struct *ndpi_str, const NDPI_PROTOCOL_BITMASK *detection_bitmask, const u_int32_t idx, u_int16_t ndpi_protocol_id, void (*func)(struct ndpi_detection_module_struct *, struct ndpi_flow_struct *flow), const NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_bitmask, u_int8_t b_save_bitmask_unknow, u_int8_t b_add_detection_bitmask) { /* Compare specify protocol bitmask with main detection bitmask */ if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(*detection_bitmask, ndpi_protocol_id) != 0) { #ifdef DEBUG NDPI_LOG_DBG2(ndpi_str, "[NDPI] ndpi_set_bitmask_protocol_detection: %s : [callback_buffer] idx= %u, [proto_defaults] " "protocol_id=%u\n", label, idx, ndpi_protocol_id); #endif if(ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx != 0) { NDPI_LOG_DBG2(ndpi_str, "[NDPI] Internal error: protocol %s/%u has been already registered\n", label, ndpi_protocol_id); #ifdef DEBUG } else { NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding %s with protocol id %d\n", label, ndpi_protocol_id); #endif } /* Set function and index protocol within proto_default structure for port protocol detection and callback_buffer function for DPI protocol detection */ ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx = idx; ndpi_str->proto_defaults[ndpi_protocol_id].func = ndpi_str->callback_buffer[idx].func = func; /* Set ndpi_selection_bitmask for protocol */ ndpi_str->callback_buffer[idx].ndpi_selection_bitmask = ndpi_selection_bitmask; /* Reset protocol detection bitmask via NDPI_PROTOCOL_UNKNOWN and than add specify protocol bitmast to callback buffer. */ if(b_save_bitmask_unknow) NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, NDPI_PROTOCOL_UNKNOWN); if(b_add_detection_bitmask) NDPI_ADD_PROTOCOL_TO_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, ndpi_protocol_id); NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].excluded_protocol_bitmask, ndpi_protocol_id); } } /* ******************************************************************** */ void ndpi_set_protocol_detection_bitmask2(struct ndpi_detection_module_struct *ndpi_str, const NDPI_PROTOCOL_BITMASK *dbm) { NDPI_PROTOCOL_BITMASK detection_bitmask_local; NDPI_PROTOCOL_BITMASK *detection_bitmask = &detection_bitmask_local; u_int32_t a = 0; NDPI_BITMASK_SET(detection_bitmask_local, *dbm); NDPI_BITMASK_SET(ndpi_str->detection_bitmask, *dbm); /* set this here to zero to be interrupt safe */ ndpi_str->callback_buffer_size = 0; /* HTTP */ init_http_dissector(ndpi_str, &a, detection_bitmask); /* STARCRAFT */ init_starcraft_dissector(ndpi_str, &a, detection_bitmask); /* TLS */ init_tls_dissector(ndpi_str, &a, detection_bitmask); /* STUN */ init_stun_dissector(ndpi_str, &a, detection_bitmask); /* RTP */ init_rtp_dissector(ndpi_str, &a, detection_bitmask); /* RTSP */ init_rtsp_dissector(ndpi_str, &a, detection_bitmask); /* RDP */ init_rdp_dissector(ndpi_str, &a, detection_bitmask); /* SIP */ init_sip_dissector(ndpi_str, &a, detection_bitmask); /* IMO */ init_imo_dissector(ndpi_str, &a, detection_bitmask); /* Teredo */ init_teredo_dissector(ndpi_str, &a, detection_bitmask); /* EDONKEY */ init_edonkey_dissector(ndpi_str, &a, detection_bitmask); /* FASTTRACK */ init_fasttrack_dissector(ndpi_str, &a, detection_bitmask); /* GNUTELLA */ init_gnutella_dissector(ndpi_str, &a, detection_bitmask); /* DIRECTCONNECT */ init_directconnect_dissector(ndpi_str, &a, detection_bitmask); /* NATS */ init_nats_dissector(ndpi_str, &a, detection_bitmask); /* APPLEJUICE */ init_applejuice_dissector(ndpi_str, &a, detection_bitmask); /* SOULSEEK */ init_soulseek_dissector(ndpi_str, &a, detection_bitmask); /* SOCKS */ init_socks_dissector(ndpi_str, &a, detection_bitmask); /* IRC */ init_irc_dissector(ndpi_str, &a, detection_bitmask); /* JABBER */ init_jabber_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_POP */ init_mail_pop_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_IMAP */ init_mail_imap_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_SMTP */ init_mail_smtp_dissector(ndpi_str, &a, detection_bitmask); /* USENET */ init_usenet_dissector(ndpi_str, &a, detection_bitmask); /* DNS */ init_dns_dissector(ndpi_str, &a, detection_bitmask); /* FILETOPIA */ init_fbzero_dissector(ndpi_str, &a, detection_bitmask); /* VMWARE */ init_vmware_dissector(ndpi_str, &a, detection_bitmask); /* NON_TCP_UDP */ init_non_tcp_udp_dissector(ndpi_str, &a, detection_bitmask); /* SOPCAST */ init_sopcast_dissector(ndpi_str, &a, detection_bitmask); /* TVUPLAYER */ init_tvuplayer_dissector(ndpi_str, &a, detection_bitmask); /* PPSTREAM */ init_ppstream_dissector(ndpi_str, &a, detection_bitmask); /* PPLIVE */ init_pplive_dissector(ndpi_str, &a, detection_bitmask); /* IAX */ init_iax_dissector(ndpi_str, &a, detection_bitmask); /* MGPC */ init_mgpc_dissector(ndpi_str, &a, detection_bitmask); /* ZATTOO */ init_zattoo_dissector(ndpi_str, &a, detection_bitmask); /* QQ */ init_qq_dissector(ndpi_str, &a, detection_bitmask); /* SSH */ init_ssh_dissector(ndpi_str, &a, detection_bitmask); /* AYIYA */ init_ayiya_dissector(ndpi_str, &a, detection_bitmask); /* THUNDER */ init_thunder_dissector(ndpi_str, &a, detection_bitmask); /* VNC */ init_vnc_dissector(ndpi_str, &a, detection_bitmask); /* TEAMVIEWER */ init_teamviewer_dissector(ndpi_str, &a, detection_bitmask); /* DHCP */ init_dhcp_dissector(ndpi_str, &a, detection_bitmask); /* STEAM */ init_steam_dissector(ndpi_str, &a, detection_bitmask); /* HALFLIFE2 */ init_halflife2_dissector(ndpi_str, &a, detection_bitmask); /* XBOX */ init_xbox_dissector(ndpi_str, &a, detection_bitmask); /* HTTP_APPLICATION_ACTIVESYNC */ init_http_activesync_dissector(ndpi_str, &a, detection_bitmask); /* SMB */ init_smb_dissector(ndpi_str, &a, detection_bitmask); /* MINING */ init_mining_dissector(ndpi_str, &a, detection_bitmask); /* TELNET */ init_telnet_dissector(ndpi_str, &a, detection_bitmask); /* NTP */ init_ntp_dissector(ndpi_str, &a, detection_bitmask); /* NFS */ init_nfs_dissector(ndpi_str, &a, detection_bitmask); /* SSDP */ init_ssdp_dissector(ndpi_str, &a, detection_bitmask); /* WORLD_OF_WARCRAFT */ init_world_of_warcraft_dissector(ndpi_str, &a, detection_bitmask); /* POSTGRES */ init_postgres_dissector(ndpi_str, &a, detection_bitmask); /* MYSQL */ init_mysql_dissector(ndpi_str, &a, detection_bitmask); /* BGP */ init_bgp_dissector(ndpi_str, &a, detection_bitmask); /* SNMP */ init_snmp_dissector(ndpi_str, &a, detection_bitmask); /* KONTIKI */ init_kontiki_dissector(ndpi_str, &a, detection_bitmask); /* ICECAST */ init_icecast_dissector(ndpi_str, &a, detection_bitmask); /* SHOUTCAST */ init_shoutcast_dissector(ndpi_str, &a, detection_bitmask); /* KERBEROS */ init_kerberos_dissector(ndpi_str, &a, detection_bitmask); /* OPENFT */ init_openft_dissector(ndpi_str, &a, detection_bitmask); /* SYSLOG */ init_syslog_dissector(ndpi_str, &a, detection_bitmask); /* DIRECT_DOWNLOAD_LINK */ init_directdownloadlink_dissector(ndpi_str, &a, detection_bitmask); /* NETBIOS */ init_netbios_dissector(ndpi_str, &a, detection_bitmask); /* MDNS */ init_mdns_dissector(ndpi_str, &a, detection_bitmask); /* IPP */ init_ipp_dissector(ndpi_str, &a, detection_bitmask); /* LDAP */ init_ldap_dissector(ndpi_str, &a, detection_bitmask); /* WARCRAFT3 */ init_warcraft3_dissector(ndpi_str, &a, detection_bitmask); /* XDMCP */ init_xdmcp_dissector(ndpi_str, &a, detection_bitmask); /* TFTP */ init_tftp_dissector(ndpi_str, &a, detection_bitmask); /* MSSQL_TDS */ init_mssql_tds_dissector(ndpi_str, &a, detection_bitmask); /* PPTP */ init_pptp_dissector(ndpi_str, &a, detection_bitmask); /* STEALTHNET */ init_stealthnet_dissector(ndpi_str, &a, detection_bitmask); /* DHCPV6 */ init_dhcpv6_dissector(ndpi_str, &a, detection_bitmask); /* AFP */ init_afp_dissector(ndpi_str, &a, detection_bitmask); /* check_mk */ init_checkmk_dissector(ndpi_str, &a, detection_bitmask); /* AIMINI */ init_aimini_dissector(ndpi_str, &a, detection_bitmask); /* FLORENSIA */ init_florensia_dissector(ndpi_str, &a, detection_bitmask); /* MAPLESTORY */ init_maplestory_dissector(ndpi_str, &a, detection_bitmask); /* DOFUS */ init_dofus_dissector(ndpi_str, &a, detection_bitmask); /* WORLD_OF_KUNG_FU */ init_world_of_kung_fu_dissector(ndpi_str, &a, detection_bitmask); /* FIESTA */ init_fiesta_dissector(ndpi_str, &a, detection_bitmask); /* CROSSIFIRE */ init_crossfire_dissector(ndpi_str, &a, detection_bitmask); /* GUILDWARS */ init_guildwars_dissector(ndpi_str, &a, detection_bitmask); /* ARMAGETRON */ init_armagetron_dissector(ndpi_str, &a, detection_bitmask); /* DROPBOX */ init_dropbox_dissector(ndpi_str, &a, detection_bitmask); /* SPOTIFY */ init_spotify_dissector(ndpi_str, &a, detection_bitmask); /* RADIUS */ init_radius_dissector(ndpi_str, &a, detection_bitmask); /* CITRIX */ init_citrix_dissector(ndpi_str, &a, detection_bitmask); /* LOTUS_NOTES */ init_lotus_notes_dissector(ndpi_str, &a, detection_bitmask); /* GTP */ init_gtp_dissector(ndpi_str, &a, detection_bitmask); /* DCERPC */ init_dcerpc_dissector(ndpi_str, &a, detection_bitmask); /* NETFLOW */ init_netflow_dissector(ndpi_str, &a, detection_bitmask); /* SFLOW */ init_sflow_dissector(ndpi_str, &a, detection_bitmask); /* H323 */ init_h323_dissector(ndpi_str, &a, detection_bitmask); /* OPENVPN */ init_openvpn_dissector(ndpi_str, &a, detection_bitmask); /* NOE */ init_noe_dissector(ndpi_str, &a, detection_bitmask); /* CISCOVPN */ init_ciscovpn_dissector(ndpi_str, &a, detection_bitmask); /* TEAMSPEAK */ init_teamspeak_dissector(ndpi_str, &a, detection_bitmask); /* TOR */ init_tor_dissector(ndpi_str, &a, detection_bitmask); /* SKINNY */ init_skinny_dissector(ndpi_str, &a, detection_bitmask); /* RTCP */ init_rtcp_dissector(ndpi_str, &a, detection_bitmask); /* RSYNC */ init_rsync_dissector(ndpi_str, &a, detection_bitmask); /* WHOIS_DAS */ init_whois_das_dissector(ndpi_str, &a, detection_bitmask); /* ORACLE */ init_oracle_dissector(ndpi_str, &a, detection_bitmask); /* CORBA */ init_corba_dissector(ndpi_str, &a, detection_bitmask); /* RTMP */ init_rtmp_dissector(ndpi_str, &a, detection_bitmask); /* FTP_CONTROL */ init_ftp_control_dissector(ndpi_str, &a, detection_bitmask); /* FTP_DATA */ init_ftp_data_dissector(ndpi_str, &a, detection_bitmask); /* PANDO */ init_pando_dissector(ndpi_str, &a, detection_bitmask); /* MEGACO */ init_megaco_dissector(ndpi_str, &a, detection_bitmask); /* REDIS */ init_redis_dissector(ndpi_str, &a, detection_bitmask); /* UPnP */ init_upnp_dissector(ndpi_str, &a, detection_bitmask); /* VHUA */ init_vhua_dissector(ndpi_str, &a, detection_bitmask); /* ZMQ */ init_zmq_dissector(ndpi_str, &a, detection_bitmask); /* TELEGRAM */ init_telegram_dissector(ndpi_str, &a, detection_bitmask); /* QUIC */ init_quic_dissector(ndpi_str, &a, detection_bitmask); /* DIAMETER */ init_diameter_dissector(ndpi_str, &a, detection_bitmask); /* APPLE_PUSH */ init_apple_push_dissector(ndpi_str, &a, detection_bitmask); /* EAQ */ init_eaq_dissector(ndpi_str, &a, detection_bitmask); /* KAKAOTALK_VOICE */ init_kakaotalk_voice_dissector(ndpi_str, &a, detection_bitmask); /* MPEGTS */ init_mpegts_dissector(ndpi_str, &a, detection_bitmask); /* UBNTAC2 */ init_ubntac2_dissector(ndpi_str, &a, detection_bitmask); /* COAP */ init_coap_dissector(ndpi_str, &a, detection_bitmask); /* MQTT */ init_mqtt_dissector(ndpi_str, &a, detection_bitmask); /* SOME/IP */ init_someip_dissector(ndpi_str, &a, detection_bitmask); /* RX */ init_rx_dissector(ndpi_str, &a, detection_bitmask); /* GIT */ init_git_dissector(ndpi_str, &a, detection_bitmask); /* HANGOUT */ init_hangout_dissector(ndpi_str, &a, detection_bitmask); /* DRDA */ init_drda_dissector(ndpi_str, &a, detection_bitmask); /* BJNP */ init_bjnp_dissector(ndpi_str, &a, detection_bitmask); /* SMPP */ init_smpp_dissector(ndpi_str, &a, detection_bitmask); /* TINC */ init_tinc_dissector(ndpi_str, &a, detection_bitmask); /* FIX */ init_fix_dissector(ndpi_str, &a, detection_bitmask); /* NINTENDO */ init_nintendo_dissector(ndpi_str, &a, detection_bitmask); /* MODBUS */ init_modbus_dissector(ndpi_str, &a, detection_bitmask); /* CAPWAP */ init_capwap_dissector(ndpi_str, &a, detection_bitmask); /* ZABBIX */ init_zabbix_dissector(ndpi_str, &a, detection_bitmask); /*** Put false-positive sensitive protocols at the end ***/ /* VIBER */ init_viber_dissector(ndpi_str, &a, detection_bitmask); /* SKYPE */ init_skype_dissector(ndpi_str, &a, detection_bitmask); /* BITTORRENT */ init_bittorrent_dissector(ndpi_str, &a, detection_bitmask); /* WHATSAPP */ init_whatsapp_dissector(ndpi_str, &a, detection_bitmask); /* OOKLA */ init_ookla_dissector(ndpi_str, &a, detection_bitmask); /* AMQP */ init_amqp_dissector(ndpi_str, &a, detection_bitmask); /* CSGO */ init_csgo_dissector(ndpi_str, &a, detection_bitmask); /* LISP */ init_lisp_dissector(ndpi_str, &a, detection_bitmask); /* AJP */ init_ajp_dissector(ndpi_str, &a, detection_bitmask); /* Memcached */ init_memcached_dissector(ndpi_str, &a, detection_bitmask); /* Nest Log Sink */ init_nest_log_sink_dissector(ndpi_str, &a, detection_bitmask); /* WireGuard VPN */ init_wireguard_dissector(ndpi_str, &a, detection_bitmask); /* Amazon_Video */ init_amazon_video_dissector(ndpi_str, &a, detection_bitmask); /* Targus Getdata */ init_targus_getdata_dissector(ndpi_str, &a, detection_bitmask); /* S7 comm */ init_s7comm_dissector(ndpi_str, &a, detection_bitmask); /* IEC 60870-5-104 */ init_104_dissector(ndpi_str, &a, detection_bitmask); /* WEBSOCKET */ init_websocket_dissector(ndpi_str, &a, detection_bitmask); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_main_init.c" #endif /* ----------------------------------------------------------------- */ ndpi_str->callback_buffer_size = a; NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size is %u\n", ndpi_str->callback_buffer_size); /* now build the specific buffer for tcp, udp and non_tcp_udp */ ndpi_str->callback_buffer_size_tcp_payload = 0; ndpi_str->callback_buffer_size_tcp_no_payload = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_tcp_payload, adding buffer %u as entry %u\n", a, ndpi_str->callback_buffer_size_tcp_payload); memcpy(&ndpi_str->callback_buffer_tcp_payload[ndpi_str->callback_buffer_size_tcp_payload], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_tcp_payload++; if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) == 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2( ndpi_str, "\tcallback_buffer_tcp_no_payload, additional adding buffer %u to no_payload process\n", a); memcpy(&ndpi_str->callback_buffer_tcp_no_payload[ndpi_str->callback_buffer_size_tcp_no_payload], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_tcp_no_payload++; } } } ndpi_str->callback_buffer_size_udp = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size_udp: adding buffer : %u as entry %u\n", a, ndpi_str->callback_buffer_size_udp); memcpy(&ndpi_str->callback_buffer_udp[ndpi_str->callback_buffer_size_udp], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_udp++; } } ndpi_str->callback_buffer_size_non_tcp_udp = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP)) == 0 || (ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_non_tcp_udp: adding buffer : %u as entry %u\n", a, ndpi_str->callback_buffer_size_non_tcp_udp); memcpy(&ndpi_str->callback_buffer_non_tcp_udp[ndpi_str->callback_buffer_size_non_tcp_udp], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_non_tcp_udp++; } } } #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* handle extension headers in IPv6 packets * arguments: * l4ptr: pointer to the byte following the initial IPv6 header * l4len: the length of the IPv6 packet excluding the IPv6 header * nxt_hdr: next header value from the IPv6 header * result: * l4ptr: pointer to the start of the actual packet payload * l4len: length of the actual payload * nxt_hdr: protocol of the actual payload * returns 0 upon success and 1 upon failure */ int ndpi_handle_ipv6_extension_headers(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t **l4ptr, u_int16_t *l4len, u_int8_t *nxt_hdr) { while ((*nxt_hdr == 0 || *nxt_hdr == 43 || *nxt_hdr == 44 || *nxt_hdr == 60 || *nxt_hdr == 135 || *nxt_hdr == 59)) { u_int16_t ehdr_len; // no next header if(*nxt_hdr == 59) { return(1); } // fragment extension header has fixed size of 8 bytes and the first byte is the next header type if(*nxt_hdr == 44) { if(*l4len < 8) { return(1); } *nxt_hdr = (*l4ptr)[0]; *l4len -= 8; (*l4ptr) += 8; continue; } // the other extension headers have one byte for the next header type // and one byte for the extension header length in 8 byte steps minus the first 8 bytes if(*l4len < 2) { return(1); } ehdr_len = (*l4ptr)[1]; ehdr_len *= 8; ehdr_len += 8; if(*l4len < ehdr_len) { return(1); } *nxt_hdr = (*l4ptr)[0]; *l4len -= ehdr_len; (*l4ptr) += ehdr_len; } return(0); } #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ static u_int8_t ndpi_iph_is_valid_and_not_fragmented(const struct ndpi_iphdr *iph, const u_int16_t ipsize) { //#ifdef REQUIRE_FULL_PACKETS if(ipsize < iph->ihl * 4 || ipsize < ntohs(iph->tot_len) || ntohs(iph->tot_len) < iph->ihl * 4 || (iph->frag_off & htons(0x1FFF)) != 0) { return(0); } //#endif return(1); } static u_int8_t ndpi_detection_get_l4_internal(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t *l3, u_int16_t l3_len, const u_int8_t **l4_return, u_int16_t *l4_len_return, u_int8_t *l4_protocol_return, u_int32_t flags) { const struct ndpi_iphdr *iph = NULL; #ifdef NDPI_DETECTION_SUPPORT_IPV6 const struct ndpi_ipv6hdr *iph_v6 = NULL; #endif u_int16_t l4len = 0; const u_int8_t *l4ptr = NULL; u_int8_t l4protocol = 0; if(l3 == NULL || l3_len < sizeof(struct ndpi_iphdr)) return(1); if((iph = (const struct ndpi_iphdr *) l3) == NULL) return(1); if(iph->version == IPVERSION && iph->ihl >= 5) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n"); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(iph->version == 6 && l3_len >= sizeof(struct ndpi_ipv6hdr)) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n"); iph_v6 = (const struct ndpi_ipv6hdr *) l3; iph = NULL; } #endif else { return(1); } if((flags & NDPI_DETECTION_ONLY_IPV6) && iph != NULL) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header found but excluded by flag\n"); return(1); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if((flags & NDPI_DETECTION_ONLY_IPV4) && iph_v6 != NULL) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header found but excluded by flag\n"); return(1); } #endif if(iph != NULL && ndpi_iph_is_valid_and_not_fragmented(iph, l3_len)) { u_int16_t len = ntohs(iph->tot_len); u_int16_t hlen = (iph->ihl * 4); l4ptr = (((const u_int8_t *) iph) + iph->ihl * 4); if(len == 0) len = l3_len; l4len = (len > hlen) ? (len - hlen) : 0; l4protocol = iph->protocol; } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(iph_v6 != NULL && (l3_len - sizeof(struct ndpi_ipv6hdr)) >= ntohs(iph_v6->ip6_hdr.ip6_un1_plen)) { l4ptr = (((const u_int8_t *) iph_v6) + sizeof(struct ndpi_ipv6hdr)); l4len = ntohs(iph_v6->ip6_hdr.ip6_un1_plen); l4protocol = iph_v6->ip6_hdr.ip6_un1_nxt; // we need to handle IPv6 extension headers if present if(ndpi_handle_ipv6_extension_headers(ndpi_str, &l4ptr, &l4len, &l4protocol) != 0) { return(1); } } #endif else { return(1); } if(l4_return != NULL) { *l4_return = l4ptr; } if(l4_len_return != NULL) { *l4_len_return = l4len; } if(l4_protocol_return != NULL) { *l4_protocol_return = l4protocol; } return(0); } /* ************************************************ */ void ndpi_apply_flow_protocol_to_packet(struct ndpi_flow_struct *flow, struct ndpi_packet_struct *packet) { memcpy(&packet->detected_protocol_stack, &flow->detected_protocol_stack, sizeof(packet->detected_protocol_stack)); memcpy(&packet->protocol_stack_info, &flow->protocol_stack_info, sizeof(packet->protocol_stack_info)); } /* ************************************************ */ static int ndpi_init_packet_header(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, unsigned short packetlen) { const struct ndpi_iphdr *decaps_iph = NULL; u_int16_t l3len; u_int16_t l4len; const u_int8_t *l4ptr; u_int8_t l4protocol; u_int8_t l4_result; if(!flow) return(1); /* reset payload_packet_len, will be set if ipv4 tcp or udp */ flow->packet.payload_packet_len = 0; flow->packet.l4_packet_len = 0; flow->packet.l3_packet_len = packetlen; flow->packet.tcp = NULL, flow->packet.udp = NULL; flow->packet.generic_l4_ptr = NULL; #ifdef NDPI_DETECTION_SUPPORT_IPV6 flow->packet.iphv6 = NULL; #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ ndpi_apply_flow_protocol_to_packet(flow, &flow->packet); l3len = flow->packet.l3_packet_len; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iph != NULL) { #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ decaps_iph = flow->packet.iph; #ifdef NDPI_DETECTION_SUPPORT_IPV6 } #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ if(decaps_iph && decaps_iph->version == IPVERSION && decaps_iph->ihl >= 5) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n"); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(decaps_iph && decaps_iph->version == 6 && l3len >= sizeof(struct ndpi_ipv6hdr) && (ndpi_str->ip_version_limit & NDPI_DETECTION_ONLY_IPV4) == 0) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n"); flow->packet.iphv6 = (struct ndpi_ipv6hdr *) flow->packet.iph; flow->packet.iph = NULL; } #endif else { flow->packet.iph = NULL; return(1); } /* needed: * - unfragmented packets * - ip header <= packet len * - ip total length >= packet len */ l4ptr = NULL; l4len = 0; l4protocol = 0; l4_result = ndpi_detection_get_l4_internal(ndpi_str, (const u_int8_t *) decaps_iph, l3len, &l4ptr, &l4len, &l4protocol, 0); if(l4_result != 0) { return(1); } flow->packet.l4_protocol = l4protocol; flow->packet.l4_packet_len = l4len; flow->l4_proto = l4protocol; /* tcp / udp detection */ if(l4protocol == IPPROTO_TCP && flow->packet.l4_packet_len >= 20 /* min size of tcp */) { /* tcp */ flow->packet.tcp = (struct ndpi_tcphdr *) l4ptr; if(flow->packet.l4_packet_len >= flow->packet.tcp->doff * 4) { flow->packet.payload_packet_len = flow->packet.l4_packet_len - flow->packet.tcp->doff * 4; flow->packet.actual_payload_len = flow->packet.payload_packet_len; flow->packet.payload = ((u_int8_t *) flow->packet.tcp) + (flow->packet.tcp->doff * 4); /* check for new tcp syn packets, here * idea: reset detection state if a connection is unknown */ if(flow->packet.tcp->syn != 0 && flow->packet.tcp->ack == 0 && flow->init_finished != 0 && flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { u_int8_t backup; u_int16_t backup1, backup2; if(flow->http.url) { ndpi_free(flow->http.url); flow->http.url = NULL; } if(flow->http.content_type) { ndpi_free(flow->http.content_type); flow->http.content_type = NULL; } if(flow->http.user_agent) { ndpi_free(flow->http.user_agent); flow->http.user_agent = NULL; } if(flow->kerberos_buf.pktbuf) { ndpi_free(flow->kerberos_buf.pktbuf); flow->kerberos_buf.pktbuf = NULL; } if(flow->l4.tcp.tls.message.buffer) { ndpi_free(flow->l4.tcp.tls.message.buffer); flow->l4.tcp.tls.message.buffer = NULL; flow->l4.tcp.tls.message.buffer_len = flow->l4.tcp.tls.message.buffer_used = 0; } backup = flow->num_processed_pkts; backup1 = flow->guessed_protocol_id; backup2 = flow->guessed_host_protocol_id; memset(flow, 0, sizeof(*(flow))); flow->num_processed_pkts = backup; flow->guessed_protocol_id = backup1; flow->guessed_host_protocol_id = backup2; NDPI_LOG_DBG(ndpi_str, "tcp syn packet for unknown protocol, reset detection state\n"); } } else { /* tcp header not complete */ flow->packet.tcp = NULL; } } else if(l4protocol == IPPROTO_UDP && flow->packet.l4_packet_len >= 8 /* size of udp */) { flow->packet.udp = (struct ndpi_udphdr *) l4ptr; flow->packet.payload_packet_len = flow->packet.l4_packet_len - 8; flow->packet.payload = ((u_int8_t *) flow->packet.udp) + 8; } else { flow->packet.generic_l4_ptr = l4ptr; } return(0); } /* ************************************************ */ void ndpi_connection_tracking(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { if(!flow) { return; } else { /* const for gcc code optimization and cleaner code */ struct ndpi_packet_struct *packet = &flow->packet; const struct ndpi_iphdr *iph = packet->iph; #ifdef NDPI_DETECTION_SUPPORT_IPV6 const struct ndpi_ipv6hdr *iphv6 = packet->iphv6; #endif const struct ndpi_tcphdr *tcph = packet->tcp; const struct ndpi_udphdr *udph = flow->packet.udp; packet->tcp_retransmission = 0, packet->packet_direction = 0; if(ndpi_str->direction_detect_disable) { packet->packet_direction = flow->packet_direction; } else { if(iph != NULL && ntohl(iph->saddr) < ntohl(iph->daddr)) packet->packet_direction = 1; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(iphv6 != NULL && NDPI_COMPARE_IPV6_ADDRESS_STRUCTS(&iphv6->ip6_src, &iphv6->ip6_dst) != 0) packet->packet_direction = 1; #endif } packet->packet_lines_parsed_complete = 0; if(flow->init_finished == 0) { flow->init_finished = 1; flow->setup_packet_direction = packet->packet_direction; } if(tcph != NULL) { /* reset retried bytes here before setting it */ packet->num_retried_bytes = 0; if(!ndpi_str->direction_detect_disable) packet->packet_direction = (ntohs(tcph->source) < ntohs(tcph->dest)) ? 1 : 0; if(tcph->syn != 0 && tcph->ack == 0 && flow->l4.tcp.seen_syn == 0 && flow->l4.tcp.seen_syn_ack == 0 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_syn = 1; } if(tcph->syn != 0 && tcph->ack != 0 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 0 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_syn_ack = 1; } if(tcph->syn == 0 && tcph->ack == 1 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 1 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_ack = 1; } if((flow->next_tcp_seq_nr[0] == 0 && flow->next_tcp_seq_nr[1] == 0) || (flow->next_tcp_seq_nr[0] == 0 || flow->next_tcp_seq_nr[1] == 0)) { /* initialize tcp sequence counters */ /* the ack flag needs to be set to get valid sequence numbers from the other * direction. Usually it will catch the second packet syn+ack but it works * also for asymmetric traffic where it will use the first data packet * * if the syn flag is set add one to the sequence number, * otherwise use the payload length. */ if(tcph->ack != 0) { flow->next_tcp_seq_nr[flow->packet.packet_direction] = ntohl(tcph->seq) + (tcph->syn ? 1 : packet->payload_packet_len); flow->next_tcp_seq_nr[1 - flow->packet.packet_direction] = ntohl(tcph->ack_seq); } } else if(packet->payload_packet_len > 0) { /* check tcp sequence counters */ if(((u_int32_t)(ntohl(tcph->seq) - flow->next_tcp_seq_nr[packet->packet_direction])) > ndpi_str->tcp_max_retransmission_window_size) { packet->tcp_retransmission = 1; /* CHECK IF PARTIAL RETRY IS HAPPENING */ if((flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq) < packet->payload_packet_len)) { /* num_retried_bytes actual_payload_len hold info about the partial retry analyzer which require this info can make use of this info Other analyzer can use packet->payload_packet_len */ packet->num_retried_bytes = (u_int16_t)(flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq)); packet->actual_payload_len = packet->payload_packet_len - packet->num_retried_bytes; flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len; } } /* normal path actual_payload_len is initialized to payload_packet_len during tcp header parsing itself. It will be changed only in case of retransmission */ else { packet->num_retried_bytes = 0; flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len; } } if(tcph->rst) { flow->next_tcp_seq_nr[0] = 0; flow->next_tcp_seq_nr[1] = 0; } } else if(udph != NULL) { if(!ndpi_str->direction_detect_disable) packet->packet_direction = (htons(udph->source) < htons(udph->dest)) ? 1 : 0; } if(flow->packet_counter < MAX_PACKET_COUNTER && packet->payload_packet_len) { flow->packet_counter++; } if(flow->packet_direction_counter[packet->packet_direction] < MAX_PACKET_COUNTER && packet->payload_packet_len) { flow->packet_direction_counter[packet->packet_direction]++; } if(flow->byte_counter[packet->packet_direction] + packet->payload_packet_len > flow->byte_counter[packet->packet_direction]) { flow->byte_counter[packet->packet_direction] += packet->payload_packet_len; } } } /* ************************************************ */ void check_ndpi_other_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { if(!flow) return; void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } for (a = 0; a < ndpi_str->callback_buffer_size_non_tcp_udp; a++) { if((func != ndpi_str->callback_buffer_non_tcp_udp[a].func) && (ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_non_tcp_udp[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_non_tcp_udp[a].detection_bitmask, detection_bitmask) != 0) { if(ndpi_str->callback_buffer_non_tcp_udp[a].func != NULL) ndpi_str->callback_buffer_non_tcp_udp[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } /* ************************************************ */ void check_ndpi_udp_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { for (a = 0; a < ndpi_str->callback_buffer_size_udp; a++) { if((func != ndpi_str->callback_buffer_udp[a].func) && (ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_udp[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_udp[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_udp[a].func(ndpi_str, flow); // NDPI_LOG_DBG(ndpi_str, "[UDP,CALL] dissector of protocol as callback_buffer idx = %d\n",a); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } else if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "[UDP,SKIP] dissector of protocol as callback_buffer idx = %d\n", a); } } } /* ************************************************ */ void check_ndpi_tcp_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if(flow->packet.payload_packet_len != 0) { if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { for (a = 0; a < ndpi_str->callback_buffer_size_tcp_payload; a++) { if((func != ndpi_str->callback_buffer_tcp_payload[a].func) && (ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_tcp_payload[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_payload[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_tcp_payload[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } } else { /* no payload */ if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL) && ((ndpi_str->callback_buffer[flow->guessed_protocol_id].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) == 0)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } for (a = 0; a < ndpi_str->callback_buffer_size_tcp_no_payload; a++) { if((func != ndpi_str->callback_buffer_tcp_payload[a].func) && (ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_tcp_no_payload[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_no_payload[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_tcp_no_payload[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } } /* ********************************************************************************* */ void ndpi_check_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { if(flow->packet.tcp != NULL) check_ndpi_tcp_flow_func(ndpi_str, flow, ndpi_selection_packet); else if(flow->packet.udp != NULL) check_ndpi_udp_flow_func(ndpi_str, flow, ndpi_selection_packet); else check_ndpi_other_flow_func(ndpi_str, flow, ndpi_selection_packet); } /* ********************************************************************************* */ u_int16_t ndpi_guess_host_protocol_id(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int16_t ret = NDPI_PROTOCOL_UNKNOWN; if(flow->packet.iph) { struct in_addr addr; u_int16_t sport, dport; addr.s_addr = flow->packet.iph->saddr; if((flow->l4_proto == IPPROTO_TCP) && flow->packet.tcp) sport = flow->packet.tcp->source, dport = flow->packet.tcp->dest; else if((flow->l4_proto == IPPROTO_UDP) && flow->packet.udp) sport = flow->packet.udp->source, dport = flow->packet.udp->dest; else sport = dport = 0; /* guess host protocol */ ret = ndpi_network_port_ptree_match(ndpi_str, &addr, sport); if(ret == NDPI_PROTOCOL_UNKNOWN) { addr.s_addr = flow->packet.iph->daddr; ret = ndpi_network_port_ptree_match(ndpi_str, &addr, dport); } } return(ret); } /* ********************************************************************************* */ ndpi_protocol ndpi_detection_giveup(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t enable_guess, u_int8_t *protocol_was_guessed) { ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; *protocol_was_guessed = 0; if(flow == NULL) return(ret); /* Init defaults */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; ret.category = flow->category; /* Ensure that we don't change our mind if detection is already complete */ if((ret.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN)) return(ret); /* TODO: add the remaining stage_XXXX protocols */ if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { u_int16_t guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN, guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN; if(flow->guessed_protocol_id == NDPI_PROTOCOL_STUN) goto check_stun_export; else if((flow->guessed_protocol_id == NDPI_PROTOCOL_HANGOUT_DUO) || (flow->guessed_protocol_id == NDPI_PROTOCOL_MESSENGER) || (flow->guessed_protocol_id == NDPI_PROTOCOL_WHATSAPP_CALL)) { *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_protocol_id, NDPI_PROTOCOL_UNKNOWN); } else if((flow->l4.tcp.tls.hello_processed == 1) && (flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0')) { *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, NDPI_PROTOCOL_TLS, NDPI_PROTOCOL_UNKNOWN); } else if(enable_guess) { if((flow->guessed_protocol_id == NDPI_PROTOCOL_UNKNOWN) && (flow->packet.l4_protocol == IPPROTO_TCP) && flow->l4.tcp.tls.hello_processed) flow->guessed_protocol_id = NDPI_PROTOCOL_TLS; guessed_protocol_id = flow->guessed_protocol_id, guessed_host_protocol_id = flow->guessed_host_protocol_id; if((guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) && ((flow->packet.l4_protocol == IPPROTO_UDP) && NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_host_protocol_id) && is_udp_guessable_protocol(guessed_host_protocol_id))) flow->guessed_host_protocol_id = guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN; /* Ignore guessed protocol if they have been discarded */ if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) // && (guessed_host_protocol_id == NDPI_PROTOCOL_UNKNOWN) && (flow->packet.l4_protocol == IPPROTO_UDP) && NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_protocol_id) && is_udp_guessable_protocol(guessed_protocol_id)) flow->guessed_protocol_id = guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN; if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) || (guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) { if((guessed_protocol_id == 0) && (flow->protos.stun_ssl.stun.num_binding_requests > 0) && (flow->protos.stun_ssl.stun.num_processed_pkts > 0)) guessed_protocol_id = NDPI_PROTOCOL_STUN; if(flow->host_server_name[0] != '\0') { ndpi_protocol_match_result ret_match; memset(&ret_match, 0, sizeof(ret_match)); ndpi_match_host_subprotocol(ndpi_str, flow, (char *) flow->host_server_name, strlen((const char *) flow->host_server_name), &ret_match, NDPI_PROTOCOL_DNS); if(ret_match.protocol_id != NDPI_PROTOCOL_UNKNOWN) guessed_host_protocol_id = ret_match.protocol_id; } *protocol_was_guessed = 1; ndpi_int_change_protocol(ndpi_str, flow, guessed_host_protocol_id, guessed_protocol_id); } } } else if(enable_guess) { if(flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; flow->detected_protocol_stack[1] = flow->guessed_protocol_id; } if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; flow->detected_protocol_stack[0] = flow->guessed_host_protocol_id; } if(flow->detected_protocol_stack[1] == flow->detected_protocol_stack[0]) { *protocol_was_guessed = 1; flow->detected_protocol_stack[1] = flow->guessed_host_protocol_id; } } if((flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) && (flow->guessed_protocol_id == NDPI_PROTOCOL_STUN)) { check_stun_export: if(flow->protos.stun_ssl.stun.num_processed_pkts || flow->protos.stun_ssl.stun.num_udp_pkts) { // if(/* (flow->protos.stun_ssl.stun.num_processed_pkts >= NDPI_MIN_NUM_STUN_DETECTION) */ *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_host_protocol_id, NDPI_PROTOCOL_STUN); } } ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(ret.master_protocol == NDPI_PROTOCOL_STUN) { if(ret.app_protocol == NDPI_PROTOCOL_FACEBOOK) ret.app_protocol = NDPI_PROTOCOL_MESSENGER; else if(ret.app_protocol == NDPI_PROTOCOL_GOOGLE) { /* As Google has recently introduced Duo, we need to distinguish between it and hangout thing that should be handled by the STUN dissector */ ret.app_protocol = NDPI_PROTOCOL_HANGOUT_DUO; } } if(ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; ndpi_fill_protocol_category(ndpi_str, flow, &ret); } return(ret); } /* ********************************************************************************* */ void ndpi_process_extra_packet(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, const unsigned char *packet, const unsigned short packetlen, const u_int64_t current_time_ms, struct ndpi_id_struct *src, struct ndpi_id_struct *dst) { if(flow == NULL) return; if(flow->server_id == NULL) flow->server_id = dst; /* Default */ /* need at least 20 bytes for ip header */ if(packetlen < 20) { return; } flow->packet.current_time_ms = current_time_ms; /* parse packet */ flow->packet.iph = (struct ndpi_iphdr *) packet; /* we are interested in ipv4 packet */ /* set up the packet headers for the extra packet function to use if it wants */ if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0) return; /* detect traffic for tcp or udp only */ flow->src = src, flow->dst = dst; ndpi_connection_tracking(ndpi_str, flow); /* call the extra packet function (which may add more data/info to flow) */ if(flow->extra_packets_func) { if((flow->extra_packets_func(ndpi_str, flow)) == 0) flow->check_extra_packets = 0; if(++flow->num_extra_packets_checked == flow->max_extra_packets_to_check) flow->extra_packets_func = NULL; /* Enough packets detected */ } } /* ********************************************************************************* */ int ndpi_load_ip_category(struct ndpi_detection_module_struct *ndpi_str, const char *ip_address_and_mask, ndpi_protocol_category_t category) { patricia_node_t *node; struct in_addr pin; int bits = 32; char *ptr; char ipbuf[64]; strncpy(ipbuf, ip_address_and_mask, sizeof(ipbuf)); ipbuf[sizeof(ipbuf) - 1] = '\0'; ptr = strrchr(ipbuf, '/'); if(ptr) { *(ptr++) = '\0'; if(atoi(ptr) >= 0 && atoi(ptr) <= 32) bits = atoi(ptr); } if(inet_pton(AF_INET, ipbuf, &pin) != 1) { NDPI_LOG_DBG2(ndpi_str, "Invalid ip/ip+netmask: %s\n", ip_address_and_mask); return(-1); } if((node = add_to_ptree(ndpi_str->custom_categories.ipAddresses_shadow, AF_INET, &pin, bits)) != NULL) { node->value.uv.user_value = (u_int16_t)category, node->value.uv.additional_user_value = 0; } return(0); } /* ********************************************************************************* */ int ndpi_load_hostname_category(struct ndpi_detection_module_struct *ndpi_str, const char *name_to_add, ndpi_protocol_category_t category) { char *name; if(name_to_add == NULL) return(-1); name = ndpi_strdup(name_to_add); if(name == NULL) return(-1); #if 0 printf("===> %s() Loading %s as %u\n", __FUNCTION__, name, category); #endif AC_PATTERN_t ac_pattern; AC_ERROR_t rc; memset(&ac_pattern, 0, sizeof(ac_pattern)); if(ndpi_str->custom_categories.hostnames_shadow.ac_automa == NULL) { free(name); return(-1); } ac_pattern.astring = name, ac_pattern.length = strlen(ac_pattern.astring); ac_pattern.rep.number = (u_int32_t) category, ac_pattern.rep.category = category;; rc = ac_automata_add(ndpi_str->custom_categories.hostnames_shadow.ac_automa, &ac_pattern); if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS) { free(name); return(-1); } if(rc == ACERR_DUPLICATE_PATTERN) free(name); return(0); } /* ********************************************************************************* */ /* Loads an IP or name category */ int ndpi_load_category(struct ndpi_detection_module_struct *ndpi_struct, const char *ip_or_name, ndpi_protocol_category_t category) { int rv; /* Try to load as IP address first */ rv = ndpi_load_ip_category(ndpi_struct, ip_or_name, category); if(rv < 0) { /* IP load failed, load as hostname */ rv = ndpi_load_hostname_category(ndpi_struct, ip_or_name, category); } return(rv); } /* ********************************************************************************* */ int ndpi_enable_loaded_categories(struct ndpi_detection_module_struct *ndpi_str) { int i; /* First add the nDPI known categories matches */ for (i = 0; category_match[i].string_to_match != NULL; i++) ndpi_load_category(ndpi_str, category_match[i].string_to_match, category_match[i].protocol_category); /* Free */ ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa, 1 /* free patterns strings memory */); /* Finalize */ ac_automata_finalize((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa); /* Swap */ ndpi_str->custom_categories.hostnames.ac_automa = ndpi_str->custom_categories.hostnames_shadow.ac_automa; /* Realloc */ ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler); if(ndpi_str->custom_categories.ipAddresses != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data); ndpi_str->custom_categories.ipAddresses = ndpi_str->custom_categories.ipAddresses_shadow; ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */); ndpi_str->custom_categories.categories_loaded = 1; return(0); } /* ********************************************************************************* */ int ndpi_fill_ip_protocol_category(struct ndpi_detection_module_struct *ndpi_str, u_int32_t saddr, u_int32_t daddr, ndpi_protocol *ret) { if(ndpi_str->custom_categories.categories_loaded) { prefix_t prefix; patricia_node_t *node; if(saddr == 0) node = NULL; else { /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, (struct in_addr *) &saddr, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); } if(!node) { if(daddr != 0) { fill_prefix_v4(&prefix, (struct in_addr *) &daddr, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); } } if(node) { ret->category = (ndpi_protocol_category_t) node->value.uv.user_value; return(1); } } ret->category = ndpi_get_proto_category(ndpi_str, *ret); return(0); } /* ********************************************************************************* */ void ndpi_fill_protocol_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol *ret) { if(ndpi_str->custom_categories.categories_loaded) { if(flow->guessed_header_category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) { flow->category = ret->category = flow->guessed_header_category; return; } if(flow->host_server_name[0] != '\0') { u_int32_t id; int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->host_server_name, strlen((char *) flow->host_server_name), &id); if(rc == 0) { flow->category = ret->category = (ndpi_protocol_category_t) id; return; } } if(flow->l4.tcp.tls.hello_processed == 1 && flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0') { u_int32_t id; int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->protos.stun_ssl.ssl.client_requested_server_name, strlen(flow->protos.stun_ssl.ssl.client_requested_server_name), &id); if(rc == 0) { flow->category = ret->category = (ndpi_protocol_category_t) id; return; } } } flow->category = ret->category = ndpi_get_proto_category(ndpi_str, *ret); } /* ********************************************************************************* */ static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; } /* ********************************************************************************* */ static int ndpi_check_protocol_port_mismatch_exceptions(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_default_ports_tree_node_t *expected_proto, ndpi_protocol *returned_proto) { /* For TLS (and other protocols) it is not simple to guess the exact protocol so before triggering an alert we need to make sure what we have exhausted all the possible options available */ if(returned_proto->master_protocol == NDPI_PROTOCOL_TLS) { switch(expected_proto->proto->protoId) { case NDPI_PROTOCOL_MAIL_IMAPS: case NDPI_PROTOCOL_MAIL_POPS: case NDPI_PROTOCOL_MAIL_SMTPS: return(1); /* This is a reasonable exception */ break; } } return(0); } /* ********************************************************************************* */ static void ndpi_reconcile_protocols(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol *ret) { /* Skype for a host doing MS Teams means MS Teams (MS Teams uses Skype as transport protocol for voice/video) */ if(flow) { /* Do not go for DNS when there is an application protocol. Example DNS.Apple */ if((flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN) && (flow->detected_protocol_stack[0] /* app */ != flow->detected_protocol_stack[1] /* major */)) NDPI_CLR_BIT(flow->risk, NDPI_SUSPICIOUS_DGA_DOMAIN); } switch(ret->app_protocol) { case NDPI_PROTOCOL_MSTEAMS: if(flow->packet.iph && flow->packet.tcp) { // printf("====>> NDPI_PROTOCOL_MSTEAMS\n"); if(ndpi_str->msteams_cache == NULL) ndpi_str->msteams_cache = ndpi_lru_cache_init(1024); if(ndpi_str->msteams_cache) ndpi_lru_add_to_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, (flow->packet.current_time_ms / 1000) & 0xFFFF /* 16 bit */); } break; case NDPI_PROTOCOL_SKYPE: case NDPI_PROTOCOL_SKYPE_CALL: if(flow->packet.iph && flow->packet.udp && ndpi_str->msteams_cache) { u_int16_t when; if(ndpi_lru_find_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, &when, 0 /* Don't remove it as it can be used for other connections */)) { u_int16_t tdiff = ((flow->packet.current_time_ms /1000) & 0xFFFF) - when; if(tdiff < 60 /* sec */) { // printf("====>> NDPI_PROTOCOL_SKYPE(_CALL) -> NDPI_PROTOCOL_MSTEAMS [%u]\n", tdiff); ret->app_protocol = NDPI_PROTOCOL_MSTEAMS; /* Refresh cache */ ndpi_lru_add_to_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, (flow->packet.current_time_ms / 1000) & 0xFFFF /* 16 bit */); } } } break; } /* switch */ } /* ********************************************************************************* */ ndpi_protocol ndpi_detection_process_packet(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, const unsigned char *packet, const unsigned short packetlen, const u_int64_t current_time_ms, struct ndpi_id_struct *src, struct ndpi_id_struct *dst) { NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_packet; u_int32_t a; ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; if(ndpi_str->ndpi_log_level >= NDPI_LOG_TRACE) NDPI_LOG(flow ? flow->detected_protocol_stack[0] : NDPI_PROTOCOL_UNKNOWN, ndpi_str, NDPI_LOG_TRACE, "START packet processing\n"); if(flow == NULL) return(ret); else ret.category = flow->category; flow->num_processed_pkts++; /* Init default */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(flow->server_id == NULL) flow->server_id = dst; /* Default */ if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) { if(flow->check_extra_packets) { ndpi_process_extra_packet(ndpi_str, flow, packet, packetlen, current_time_ms, src, dst); /* Update in case of new match */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0], ret.category = flow->category; goto invalidate_ptr; } else goto ret_protocols; } /* need at least 20 bytes for ip header */ if(packetlen < 20) { /* reset protocol which is normally done in init_packet_header */ ndpi_int_reset_packet_protocol(&flow->packet); goto invalidate_ptr; } flow->packet.current_time_ms = current_time_ms; /* parse packet */ flow->packet.iph = (struct ndpi_iphdr *) packet; /* we are interested in ipv4 packet */ if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0) goto invalidate_ptr; /* detect traffic for tcp or udp only */ flow->src = src, flow->dst = dst; ndpi_connection_tracking(ndpi_str, flow); /* build ndpi_selection packet bitmask */ ndpi_selection_packet = NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC; if(flow->packet.iph != NULL) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IP | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6; if(flow->packet.tcp != NULL) ndpi_selection_packet |= (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP); if(flow->packet.udp != NULL) ndpi_selection_packet |= (NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP); if(flow->packet.payload_packet_len != 0) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD; if(flow->packet.tcp_retransmission == 0) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_NO_TCP_RETRANSMISSION; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iphv6 != NULL) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IPV6 | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6; #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ if((!flow->protocol_id_already_guessed) && ( #ifdef NDPI_DETECTION_SUPPORT_IPV6 flow->packet.iphv6 || #endif flow->packet.iph)) { u_int16_t sport, dport; u_int8_t protocol; u_int8_t user_defined_proto; flow->protocol_id_already_guessed = 1; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iphv6 != NULL) { protocol = flow->packet.iphv6->ip6_hdr.ip6_un1_nxt; } else #endif { protocol = flow->packet.iph->protocol; } if(flow->packet.udp) sport = ntohs(flow->packet.udp->source), dport = ntohs(flow->packet.udp->dest); else if(flow->packet.tcp) sport = ntohs(flow->packet.tcp->source), dport = ntohs(flow->packet.tcp->dest); else sport = dport = 0; /* guess protocol */ flow->guessed_protocol_id = (int16_t) ndpi_guess_protocol_id(ndpi_str, flow, protocol, sport, dport, &user_defined_proto); flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow); if(ndpi_str->custom_categories.categories_loaded && flow->packet.iph) { ndpi_fill_ip_protocol_category(ndpi_str, flow->packet.iph->saddr, flow->packet.iph->daddr, &ret); flow->guessed_header_category = ret.category; } else flow->guessed_header_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED; if(flow->guessed_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) { /* This is a custom protocol and it has priority over everything else */ ret.master_protocol = NDPI_PROTOCOL_UNKNOWN, ret.app_protocol = flow->guessed_protocol_id ? flow->guessed_protocol_id : flow->guessed_host_protocol_id; ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } if(user_defined_proto && flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) { if(flow->packet.iph) { if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { u_int8_t protocol_was_guessed; /* ret.master_protocol = flow->guessed_protocol_id , ret.app_protocol = flow->guessed_host_protocol_id; /\* ****** *\/ */ ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed); } ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } } else { /* guess host protocol */ if(flow->packet.iph) { flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow); /* We could implement a shortcut here skipping dissectors for protocols we have identified by other means such as with the IP However we do NOT stop here and skip invoking the dissectors because we want to dissect the flow (e.g. dissect the TLS) and extract metadata. */ #if SKIP_INVOKING_THE_DISSECTORS if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { /* We have identified a protocol using the IP address so it is not worth to dissect the traffic as we already have the solution */ ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id; } #endif } } } if(flow->guessed_host_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) { /* This is a custom protocol and it has priority over everything else */ ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id; ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet); ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet); a = flow->packet.detected_protocol_stack[0]; if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_str->detection_bitmask, a) == 0) a = NDPI_PROTOCOL_UNKNOWN; if(a != NDPI_PROTOCOL_UNKNOWN) { int i; for (i = 0; i < sizeof(flow->host_server_name); i++) { if(flow->host_server_name[i] != '\0') flow->host_server_name[i] = tolower(flow->host_server_name[i]); else { flow->host_server_name[i] = '\0'; break; } } } ret_protocols: if(flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN) { ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(ret.app_protocol == ret.master_protocol) ret.master_protocol = NDPI_PROTOCOL_UNKNOWN; } else ret.app_protocol = flow->detected_protocol_stack[0]; /* Don't overwrite the category if already set */ if((flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN)) ndpi_fill_protocol_category(ndpi_str, flow, &ret); else ret.category = flow->category; if((flow->num_processed_pkts == 1) && (ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol == NDPI_PROTOCOL_UNKNOWN) && flow->packet.tcp && (flow->packet.tcp->syn == 0) && (flow->guessed_protocol_id == 0)) { u_int8_t protocol_was_guessed; /* This is a TCP flow - whose first packet is NOT a SYN - no protocol has been detected We don't see how future packets can match anything hence we giveup here */ ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed); } if((ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) && (flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) { ret.master_protocol = ret.app_protocol; ret.app_protocol = flow->guessed_host_protocol_id; } if((!flow->risk_checked) && (ret.master_protocol != NDPI_PROTOCOL_UNKNOWN)) { ndpi_default_ports_tree_node_t *found; u_int16_t *default_ports, sport, dport; if(flow->packet.udp) found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_UDP, sport = ntohs(flow->packet.udp->source), dport = ntohs(flow->packet.udp->dest)), default_ports = ndpi_str->proto_defaults[ret.master_protocol].udp_default_ports; else if(flow->packet.tcp) found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_TCP, sport = ntohs(flow->packet.tcp->source), dport = ntohs(flow->packet.tcp->dest)), default_ports = ndpi_str->proto_defaults[ret.master_protocol].tcp_default_ports; else found = NULL, default_ports = NULL; if(found && (found->proto->protoId != NDPI_PROTOCOL_UNKNOWN) && (found->proto->protoId != ret.master_protocol)) { // printf("******** %u / %u\n", found->proto->protoId, ret.master_protocol); if(!ndpi_check_protocol_port_mismatch_exceptions(ndpi_str, flow, found, &ret)) NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT); } else if(default_ports && (default_ports[0] != 0)) { u_int8_t found = 0, i; for(i=0; (i<MAX_DEFAULT_PORTS) && (default_ports[i] != 0); i++) { if((default_ports[i] == sport) || (default_ports[i] == dport)) { found = 1; break; } } /* for */ if(!found) { // printf("******** Invalid default port\n"); NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT); } } flow->risk_checked = 1; } ndpi_reconcile_protocols(ndpi_str, flow, &ret); invalidate_ptr: /* Invalidate packet memory to avoid accessing the pointers below when the packet is no longer accessible */ flow->packet.iph = NULL, flow->packet.tcp = NULL, flow->packet.udp = NULL, flow->packet.payload = NULL; ndpi_reset_packet_line_info(&flow->packet); return(ret); } /* ********************************************************************************* */ u_int32_t ndpi_bytestream_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; val = 0; // cancel if eof, ' ' or line end chars are reached while (*str >= '0' && *str <= '9' && max_chars_to_read > 0) { val *= 10; val += *str - '0'; str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } return(val); } /* ********************************************************************************* */ #ifdef CODE_UNUSED u_int32_t ndpi_bytestream_dec_or_hex_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; val = 0; if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') { return(ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read)); } else { /*use base 16 system */ str += 2; max_chars_to_read -= 2; *bytes_read = *bytes_read + 2; while (max_chars_to_read > 0) { if(*str >= '0' && *str <= '9') { val *= 16; val += *str - '0'; } else if(*str >= 'a' && *str <= 'f') { val *= 16; val += *str + 10 - 'a'; } else if(*str >= 'A' && *str <= 'F') { val *= 16; val += *str + 10 - 'A'; } else { break; } str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } } return(val); } #endif /* ********************************************************************************* */ u_int64_t ndpi_bytestream_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int64_t val; val = 0; // cancel if eof, ' ' or line end chars are reached while (max_chars_to_read > 0 && *str >= '0' && *str <= '9') { val *= 10; val += *str - '0'; str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } return(val); } /* ********************************************************************************* */ u_int64_t ndpi_bytestream_dec_or_hex_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int64_t val; val = 0; if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') { return(ndpi_bytestream_to_number64(str, max_chars_to_read, bytes_read)); } else { /*use base 16 system */ str += 2; max_chars_to_read -= 2; *bytes_read = *bytes_read + 2; while (max_chars_to_read > 0) { if(*str >= '0' && *str <= '9') { val *= 16; val += *str - '0'; } else if(*str >= 'a' && *str <= 'f') { val *= 16; val += *str + 10 - 'a'; } else if(*str >= 'A' && *str <= 'F') { val *= 16; val += *str + 10 - 'A'; } else { break; } str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } } return(val); } /* ********************************************************************************* */ u_int32_t ndpi_bytestream_to_ipv4(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; u_int16_t read = 0; u_int16_t oldread; u_int32_t c; /* ip address must be X.X.X.X with each X between 0 and 255 */ oldread = read; c = ndpi_bytestream_to_number(str, max_chars_to_read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = c << 24; oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = val + (c << 16); oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = val + (c << 8); oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read) return(0); val = val + c; *bytes_read = *bytes_read + read; return(htonl(val)); } /* ********************************************************************************* */ /* internal function for every detection to parse one packet and to increase the info buffer */ void ndpi_parse_packet_line_info(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int32_t a; struct ndpi_packet_struct *packet = &flow->packet; if((packet->payload_packet_len < 3) || (packet->payload == NULL)) return; if(packet->packet_lines_parsed_complete != 0) return; packet->packet_lines_parsed_complete = 1; ndpi_reset_packet_line_info(packet); packet->line[packet->parsed_lines].ptr = packet->payload; packet->line[packet->parsed_lines].len = 0; for (a = 0; ((a+1) < packet->payload_packet_len) && (packet->parsed_lines < NDPI_MAX_PARSE_LINES_PER_PACKET); a++) { if((packet->payload[a] == 0x0d) && (packet->payload[a+1] == 0x0a)) { /* If end of line char sequence CR+NL "\r\n", process line */ if(((a + 3) < packet->payload_packet_len) && (packet->payload[a+2] == 0x0d) && (packet->payload[a+3] == 0x0a)) { /* \r\n\r\n */ int diff; /* No unsigned ! */ u_int32_t a1 = a + 4; diff = packet->payload_packet_len - a1; if(diff > 0) { diff = ndpi_min(diff, sizeof(flow->initial_binary_bytes)); memcpy(&flow->initial_binary_bytes, &packet->payload[a1], diff); flow->initial_binary_bytes_len = diff; } } packet->line[packet->parsed_lines].len = (u_int16_t)(((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); /* First line of a HTTP response parsing. Expected a "HTTP/1.? ???" */ if(packet->parsed_lines == 0 && packet->line[0].len >= NDPI_STATICSTRING_LEN("HTTP/1.X 200 ") && strncasecmp((const char *) packet->line[0].ptr, "HTTP/1.", NDPI_STATICSTRING_LEN("HTTP/1.")) == 0 && packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] > '0' && /* response code between 000 and 699 */ packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] < '6') { packet->http_response.ptr = &packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.1 ")]; packet->http_response.len = packet->line[0].len - NDPI_STATICSTRING_LEN("HTTP/1.1 "); packet->http_num_headers++; /* Set server HTTP response code */ if(packet->payload_packet_len >= 12) { char buf[4]; /* Set server HTTP response code */ strncpy(buf, (char *) &packet->payload[9], 3); buf[3] = '\0'; flow->http.response_status_code = atoi(buf); /* https://en.wikipedia.org/wiki/List_of_HTTP_status_codes */ if((flow->http.response_status_code < 100) || (flow->http.response_status_code > 509)) flow->http.response_status_code = 0; /* Out of range */ } } /* "Server:" header line in HTTP response */ if(packet->line[packet->parsed_lines].len > NDPI_STATICSTRING_LEN("Server:") + 1 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Server:", NDPI_STATICSTRING_LEN("Server:")) == 0) { // some stupid clients omit a space and place the servername directly after the colon if(packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")] == ' ') { packet->server_line.ptr = &packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:") + 1]; packet->server_line.len = packet->line[packet->parsed_lines].len - (NDPI_STATICSTRING_LEN("Server:") + 1); } else { packet->server_line.ptr = &packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")]; packet->server_line.len = packet->line[packet->parsed_lines].len - NDPI_STATICSTRING_LEN("Server:"); } packet->http_num_headers++; } /* "Host:" header line in HTTP request */ if(packet->line[packet->parsed_lines].len > 6 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Host:", 5) == 0) { // some stupid clients omit a space and place the hostname directly after the colon if(packet->line[packet->parsed_lines].ptr[5] == ' ') { packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[6]; packet->host_line.len = packet->line[packet->parsed_lines].len - 6; } else { packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[5]; packet->host_line.len = packet->line[packet->parsed_lines].len - 5; } packet->http_num_headers++; } /* "X-Forwarded-For:" header line in HTTP request. Commonly used for HTTP proxies. */ if(packet->line[packet->parsed_lines].len > 17 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Forwarded-For:", 16) == 0) { // some stupid clients omit a space and place the hostname directly after the colon if(packet->line[packet->parsed_lines].ptr[16] == ' ') { packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[17]; packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 17; } else { packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 16; } packet->http_num_headers++; } /* "Content-Type:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 14 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Type: ", 14) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type: ", 14) == 0)) { packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[14]; packet->content_line.len = packet->line[packet->parsed_lines].len - 14; while ((packet->content_line.len > 0) && (packet->content_line.ptr[0] == ' ')) packet->content_line.len--, packet->content_line.ptr++; packet->http_num_headers++; } /* "Content-Type:" header line in HTTP AGAIN. Probably a bogus response without space after ":" */ if((packet->content_line.len == 0) && (packet->line[packet->parsed_lines].len > 13) && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type:", 13) == 0)) { packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[13]; packet->content_line.len = packet->line[packet->parsed_lines].len - 13; packet->http_num_headers++; } if(packet->content_line.len > 0) { /* application/json; charset=utf-8 */ char separator[] = {';', '\r', '\0'}; int i; for (i = 0; separator[i] != '\0'; i++) { char *c = memchr((char *) packet->content_line.ptr, separator[i], packet->content_line.len); if(c != NULL) packet->content_line.len = c - (char *) packet->content_line.ptr; } } /* "Accept:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept: ", 8) == 0) { packet->accept_line.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->accept_line.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "Referer:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 9 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Referer: ", 9) == 0) { packet->referer_line.ptr = &packet->line[packet->parsed_lines].ptr[9]; packet->referer_line.len = packet->line[packet->parsed_lines].len - 9; packet->http_num_headers++; } /* "User-Agent:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 12 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-Agent: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-agent: ", 12) == 0)) { packet->user_agent_line.ptr = &packet->line[packet->parsed_lines].ptr[12]; packet->user_agent_line.len = packet->line[packet->parsed_lines].len - 12; packet->http_num_headers++; } /* "Content-Encoding:" header line in HTTP response (and request?). */ if(packet->line[packet->parsed_lines].len > 18 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Encoding: ", 18) == 0) { packet->http_encoding.ptr = &packet->line[packet->parsed_lines].ptr[18]; packet->http_encoding.len = packet->line[packet->parsed_lines].len - 18; packet->http_num_headers++; } /* "Transfer-Encoding:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 19 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Transfer-Encoding: ", 19) == 0) { packet->http_transfer_encoding.ptr = &packet->line[packet->parsed_lines].ptr[19]; packet->http_transfer_encoding.len = packet->line[packet->parsed_lines].len - 19; packet->http_num_headers++; } /* "Content-Length:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 16 && ((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Length: ", 16) == 0) || (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "content-length: ", 16) == 0))) { packet->http_contentlen.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->http_contentlen.len = packet->line[packet->parsed_lines].len - 16; packet->http_num_headers++; } /* "Content-Disposition"*/ if(packet->line[packet->parsed_lines].len > 21 && ((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Disposition: ", 21) == 0))) { packet->content_disposition_line.ptr = &packet->line[packet->parsed_lines].ptr[21]; packet->content_disposition_line.len = packet->line[packet->parsed_lines].len - 21; packet->http_num_headers++; } /* "Cookie:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Cookie: ", 8) == 0) { packet->http_cookie.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->http_cookie.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "Origin:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Origin: ", 8) == 0) { packet->http_origin.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->http_origin.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "X-Session-Type:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 16 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Session-Type: ", 16) == 0) { packet->http_x_session_type.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->http_x_session_type.len = packet->line[packet->parsed_lines].len - 16; packet->http_num_headers++; } /* Identification and counting of other HTTP headers. * We consider the most common headers, but there are many others, * which can be seen at references below: * - https://tools.ietf.org/html/rfc7230 * - https://en.wikipedia.org/wiki/List_of_HTTP_header_fields */ if((packet->line[packet->parsed_lines].len > 6 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Date: ", 6) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Vary: ", 6) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "ETag: ", 6) == 0)) || (packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Pragma: ", 8) == 0) || (packet->line[packet->parsed_lines].len > 9 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Expires: ", 9) == 0) || (packet->line[packet->parsed_lines].len > 12 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Set-Cookie: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Keep-Alive: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Connection: ", 12) == 0)) || (packet->line[packet->parsed_lines].len > 15 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Last-Modified: ", 15) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Ranges: ", 15) == 0)) || (packet->line[packet->parsed_lines].len > 17 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Language: ", 17) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Encoding: ", 17) == 0)) || (packet->line[packet->parsed_lines].len > 27 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Upgrade-Insecure-Requests: ", 27) == 0)) { /* Just count. In the future, if needed, this if can be splited to parse these headers */ packet->http_num_headers++; } if(packet->line[packet->parsed_lines].len == 0) { packet->empty_line_position = a; packet->empty_line_position_set = 1; } if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1)) return; packet->parsed_lines++; packet->line[packet->parsed_lines].ptr = &packet->payload[a + 2]; packet->line[packet->parsed_lines].len = 0; a++; /* next char in the payload */ } } if(packet->parsed_lines >= 1) { packet->line[packet->parsed_lines].len = (u_int16_t)(((unsigned long) &packet->payload[packet->payload_packet_len]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); packet->parsed_lines++; } } /* ********************************************************************************* */ void ndpi_parse_packet_line_info_any(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t a; u_int16_t end = packet->payload_packet_len; if(packet->packet_lines_parsed_complete != 0) return; packet->packet_lines_parsed_complete = 1; packet->parsed_lines = 0; if(packet->payload_packet_len == 0) return; packet->line[packet->parsed_lines].ptr = packet->payload; packet->line[packet->parsed_lines].len = 0; for (a = 0; a < end; a++) { if(packet->payload[a] == 0x0a) { packet->line[packet->parsed_lines].len = (u_int16_t)( ((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); if(a > 0 && packet->payload[a - 1] == 0x0d) packet->line[packet->parsed_lines].len--; if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1)) break; packet->parsed_lines++; packet->line[packet->parsed_lines].ptr = &packet->payload[a + 1]; packet->line[packet->parsed_lines].len = 0; if((a + 1) >= packet->payload_packet_len) break; //a++; } } } /* ********************************************************************************* */ u_int16_t ndpi_check_for_email_address(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t counter) { struct ndpi_packet_struct *packet = &flow->packet; NDPI_LOG_DBG2(ndpi_str, "called ndpi_check_for_email_address\n"); if(packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_')) { NDPI_LOG_DBG2(ndpi_str, "first letter\n"); counter++; while (packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_' || packet->payload[counter] == '.')) { NDPI_LOG_DBG2(ndpi_str, "further letter\n"); counter++; if(packet->payload_packet_len > counter && packet->payload[counter] == '@') { NDPI_LOG_DBG2(ndpi_str, "@\n"); counter++; while (packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_')) { NDPI_LOG_DBG2(ndpi_str, "letter\n"); counter++; if(packet->payload_packet_len > counter && packet->payload[counter] == '.') { NDPI_LOG_DBG2(ndpi_str, ".\n"); counter++; if(packet->payload_packet_len > counter + 1 && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') && (packet->payload[counter + 1] >= 'a' && packet->payload[counter + 1] <= 'z'))) { NDPI_LOG_DBG2(ndpi_str, "two letters\n"); counter += 2; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace1\n"); return(counter); } else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') { NDPI_LOG_DBG2(ndpi_str, "one letter\n"); counter++; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace2\n"); return(counter); } else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') { counter++; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace3\n"); return(counter); } else { return(0); } } else { return(0); } } else { return(0); } } else { return(0); } } } return(0); } } } return(0); } #ifdef NDPI_ENABLE_DEBUG_MESSAGES /* ********************************************************************************* */ void ndpi_debug_get_last_log_function_line(struct ndpi_detection_module_struct *ndpi_str, const char **file, const char **func, u_int32_t *line) { *file = ""; *func = ""; if(ndpi_str->ndpi_debug_print_file != NULL) *file = ndpi_str->ndpi_debug_print_file; if(ndpi_str->ndpi_debug_print_function != NULL) *func = ndpi_str->ndpi_debug_print_function; *line = ndpi_str->ndpi_debug_print_line; } #endif /* ********************************************************************************* */ u_int8_t ndpi_detection_get_l4(const u_int8_t *l3, u_int16_t l3_len, const u_int8_t **l4_return, u_int16_t *l4_len_return, u_int8_t *l4_protocol_return, u_int32_t flags) { return(ndpi_detection_get_l4_internal(NULL, l3, l3_len, l4_return, l4_len_return, l4_protocol_return, flags)); } /* ********************************************************************************* */ void ndpi_set_detected_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { struct ndpi_id_struct *src = flow->src, *dst = flow->dst; ndpi_int_change_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); if(src != NULL) { NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, upper_detected_protocol); if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN) NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, lower_detected_protocol); } if(dst != NULL) { NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, upper_detected_protocol); if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN) NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, lower_detected_protocol); } } /* ********************************************************************************* */ u_int16_t ndpi_get_flow_masterprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { return(flow->detected_protocol_stack[1]); } /* ********************************************************************************* */ void ndpi_int_change_flow_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { if(!flow) return; flow->detected_protocol_stack[0] = upper_detected_protocol, flow->detected_protocol_stack[1] = lower_detected_protocol; } /* ********************************************************************************* */ void ndpi_int_change_packet_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { struct ndpi_packet_struct *packet = &flow->packet; /* NOTE: everything below is identically to change_flow_protocol * except flow->packet If you want to change something here, * don't! Change it for the flow function and apply it here * as well */ if(!packet) return; packet->detected_protocol_stack[0] = upper_detected_protocol, packet->detected_protocol_stack[1] = lower_detected_protocol; } /* ********************************************************************************* */ /* generic function for changing the protocol * * what it does is: * 1.update the flow protocol stack with the new protocol * 2.update the packet protocol stack with the new protocol */ void ndpi_int_change_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { if((upper_detected_protocol == NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN)) upper_detected_protocol = lower_detected_protocol; if(upper_detected_protocol == lower_detected_protocol) lower_detected_protocol = NDPI_PROTOCOL_UNKNOWN; if((upper_detected_protocol != NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol == NDPI_PROTOCOL_UNKNOWN)) { if((flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (upper_detected_protocol != flow->guessed_host_protocol_id)) { if(ndpi_str->proto_defaults[upper_detected_protocol].can_have_a_subprotocol) { lower_detected_protocol = upper_detected_protocol; upper_detected_protocol = flow->guessed_host_protocol_id; } } } ndpi_int_change_flow_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); ndpi_int_change_packet_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); } /* ********************************************************************************* */ void ndpi_int_change_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol_category_t protocol_category) { flow->category = protocol_category; } /* ********************************************************************************* */ /* turns a packet back to unknown */ void ndpi_int_reset_packet_protocol(struct ndpi_packet_struct *packet) { int a; for (a = 0; a < NDPI_PROTOCOL_SIZE; a++) packet->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN; } /* ********************************************************************************* */ void ndpi_int_reset_protocol(struct ndpi_flow_struct *flow) { if(flow) { int a; for (a = 0; a < NDPI_PROTOCOL_SIZE; a++) flow->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN; } } /* ********************************************************************************* */ void NDPI_PROTOCOL_IP_clear(ndpi_ip_addr_t *ip) { memset(ip, 0, sizeof(ndpi_ip_addr_t)); } /* ********************************************************************************* */ #ifdef CODE_UNUSED /* NTOP */ int NDPI_PROTOCOL_IP_is_set(const ndpi_ip_addr_t *ip) { return(memcmp(ip, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(ndpi_ip_addr_t)) != 0); } #endif /* ********************************************************************************* */ /* check if the source ip address in packet and ip are equal */ /* NTOP */ int ndpi_packet_src_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { if(packet->iphv6->ip6_src.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] && packet->iphv6->ip6_src.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] && packet->iphv6->ip6_src.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] && packet->iphv6->ip6_src.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3]) return(1); //else return(0); } #endif /* IPv4 */ if(packet->iph->saddr == ip->ipv4) return(1); return(0); } /* ********************************************************************************* */ /* check if the destination ip address in packet and ip are equal */ int ndpi_packet_dst_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { if(packet->iphv6->ip6_dst.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3]) return(1); //else return(0); } #endif /* IPv4 */ if(packet->iph->saddr == ip->ipv4) return(1); return(0); } /* ********************************************************************************* */ /* get the source ip address from packet and put it into ip */ /* NTOP */ void ndpi_packet_src_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) { NDPI_PROTOCOL_IP_clear(ip); #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_src.u6_addr.u6_addr32[0]; ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_src.u6_addr.u6_addr32[1]; ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_src.u6_addr.u6_addr32[2]; ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_src.u6_addr.u6_addr32[3]; } else #endif /* IPv4 */ ip->ipv4 = packet->iph->saddr; } /* ********************************************************************************* */ /* get the destination ip address from packet and put it into ip */ /* NTOP */ void ndpi_packet_dst_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) { NDPI_PROTOCOL_IP_clear(ip); #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(packet->iphv6 != NULL) { ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[0]; ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[1]; ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[2]; ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[3]; } else #endif ip->ipv4 = packet->iph->daddr; } /* ********************************************************************************* */ u_int8_t ndpi_is_ipv6(const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 return(ip->ipv6.u6_addr.u6_addr32[1] != 0 || ip->ipv6.u6_addr.u6_addr32[2] != 0 || ip->ipv6.u6_addr.u6_addr32[3] != 0); #else return(0); #endif } /* ********************************************************************************* */ char *ndpi_get_ip_string(const ndpi_ip_addr_t *ip, char *buf, u_int buf_len) { const u_int8_t *a = (const u_int8_t *) &ip->ipv4; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(ndpi_is_ipv6(ip)) { if(inet_ntop(AF_INET6, &ip->ipv6.u6_addr, buf, buf_len) == NULL) buf[0] = '\0'; return(buf); } #endif snprintf(buf, buf_len, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]); return(buf); } /* ****************************************************** */ /* Returns -1 on failutre, otherwise fills parsed_ip and returns the IP version */ int ndpi_parse_ip_string(const char *ip_str, ndpi_ip_addr_t *parsed_ip) { int rv = -1; memset(parsed_ip, 0, sizeof(*parsed_ip)); if(strchr(ip_str, '.')) { if(inet_pton(AF_INET, ip_str, &parsed_ip->ipv4) > 0) rv = 4; #ifdef NDPI_DETECTION_SUPPORT_IPV6 } else { if(inet_pton(AF_INET6, ip_str, &parsed_ip->ipv6) > 0) rv = 6; #endif } return(rv); } /* ****************************************************** */ u_int16_t ntohs_ndpi_bytestream_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int16_t val = ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read); return(ntohs(val)); } /* ****************************************************** */ u_int8_t ndpi_is_proto(ndpi_protocol proto, u_int16_t p) { return(((proto.app_protocol == p) || (proto.master_protocol == p)) ? 1 : 0); } /* ****************************************************** */ u_int16_t ndpi_get_lower_proto(ndpi_protocol proto) { return((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) ? proto.master_protocol : proto.app_protocol); } /* ****************************************************** */ ndpi_protocol ndpi_guess_undetected_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t proto, u_int32_t shost /* host byte order */, u_int16_t sport, u_int32_t dhost /* host byte order */, u_int16_t dport) { u_int32_t rc; struct in_addr addr; ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; u_int8_t user_defined_proto; if((proto == IPPROTO_TCP) || (proto == IPPROTO_UDP)) { rc = ndpi_search_tcp_or_udp_raw(ndpi_str, flow, proto, shost, dhost, sport, dport); if(rc != NDPI_PROTOCOL_UNKNOWN) { if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc)) ; else { ret.app_protocol = rc, ret.master_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); if(ret.app_protocol == ret.master_protocol) ret.master_protocol = NDPI_PROTOCOL_UNKNOWN; ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } } rc = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); if(rc != NDPI_PROTOCOL_UNKNOWN) { if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc)) ; else { ret.app_protocol = rc; if(rc == NDPI_PROTOCOL_TLS) goto check_guessed_skype; else { ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } } } check_guessed_skype: addr.s_addr = htonl(shost); if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE) { ret.app_protocol = NDPI_PROTOCOL_SKYPE; } else { addr.s_addr = htonl(dhost); if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE) ret.app_protocol = NDPI_PROTOCOL_SKYPE; } } else ret.app_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } /* ****************************************************** */ char *ndpi_protocol2id(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto, char *buf, u_int buf_len) { if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) { if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN) snprintf(buf, buf_len, "%u.%u", proto.master_protocol, proto.app_protocol); else snprintf(buf, buf_len, "%u", proto.master_protocol); } else snprintf(buf, buf_len, "%u", proto.app_protocol); return(buf); } /* ****************************************************** */ char *ndpi_protocol2name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto, char *buf, u_int buf_len) { if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) { if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN) snprintf(buf, buf_len, "%s.%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol), ndpi_get_proto_name(ndpi_str, proto.app_protocol)); else snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol)); } else snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.app_protocol)); return(buf); } /* ****************************************************** */ int ndpi_is_custom_category(ndpi_protocol_category_t category) { switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: return(1); break; default: return(0); break; } } /* ****************************************************** */ void ndpi_category_set_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_category_t category, char *name) { if(!name) return; switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: snprintf(ndpi_str->custom_category_labels[0], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: snprintf(ndpi_str->custom_category_labels[1], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: snprintf(ndpi_str->custom_category_labels[2], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: snprintf(ndpi_str->custom_category_labels[3], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: snprintf(ndpi_str->custom_category_labels[4], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; default: break; } } /* ****************************************************** */ const char *ndpi_category_get_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_category_t category) { if((!ndpi_str) || (category >= NDPI_PROTOCOL_NUM_CATEGORIES)) { static char b[24]; if(!ndpi_str) snprintf(b, sizeof(b), "NULL nDPI"); else snprintf(b, sizeof(b), "Invalid category %d", (int) category); return(b); } if((category >= NDPI_PROTOCOL_CATEGORY_CUSTOM_1) && (category <= NDPI_PROTOCOL_CATEGORY_CUSTOM_5)) { switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: return(ndpi_str->custom_category_labels[0]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: return(ndpi_str->custom_category_labels[1]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: return(ndpi_str->custom_category_labels[2]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: return(ndpi_str->custom_category_labels[3]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: return(ndpi_str->custom_category_labels[4]); case NDPI_PROTOCOL_NUM_CATEGORIES: return("Code should not use this internal constant"); default: return("Unspecified"); } } else return(categories[category]); } /* ****************************************************** */ ndpi_protocol_category_t ndpi_get_proto_category(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto) { if(proto.category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) return(proto.category); /* simple rule: sub protocol first, master after */ else if((proto.master_protocol == NDPI_PROTOCOL_UNKNOWN) || (ndpi_str->proto_defaults[proto.app_protocol].protoCategory != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) { if(proto.app_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) return(ndpi_str->proto_defaults[proto.app_protocol].protoCategory); } else if(proto.master_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) return(ndpi_str->proto_defaults[proto.master_protocol].protoCategory); return(NDPI_PROTOCOL_CATEGORY_UNSPECIFIED); } /* ****************************************************** */ char *ndpi_get_proto_name(struct ndpi_detection_module_struct *ndpi_str, u_int16_t proto_id) { if((proto_id >= ndpi_str->ndpi_num_supported_protocols) || (proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) || (ndpi_str->proto_defaults[proto_id].protoName == NULL)) proto_id = NDPI_PROTOCOL_UNKNOWN; return(ndpi_str->proto_defaults[proto_id].protoName); } /* ****************************************************** */ ndpi_protocol_breed_t ndpi_get_proto_breed(struct ndpi_detection_module_struct *ndpi_str, u_int16_t proto_id) { if((proto_id >= ndpi_str->ndpi_num_supported_protocols) || (proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) || (ndpi_str->proto_defaults[proto_id].protoName == NULL)) proto_id = NDPI_PROTOCOL_UNKNOWN; return(ndpi_str->proto_defaults[proto_id].protoBreed); } /* ****************************************************** */ char *ndpi_get_proto_breed_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_breed_t breed_id) { switch (breed_id) { case NDPI_PROTOCOL_SAFE: return("Safe"); break; case NDPI_PROTOCOL_ACCEPTABLE: return("Acceptable"); break; case NDPI_PROTOCOL_FUN: return("Fun"); break; case NDPI_PROTOCOL_UNSAFE: return("Unsafe"); break; case NDPI_PROTOCOL_POTENTIALLY_DANGEROUS: return("Potentially Dangerous"); break; case NDPI_PROTOCOL_DANGEROUS: return("Dangerous"); break; case NDPI_PROTOCOL_UNRATED: default: return("Unrated"); break; } } /* ****************************************************** */ int ndpi_get_protocol_id(struct ndpi_detection_module_struct *ndpi_str, char *proto) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) if(strcasecmp(proto, ndpi_str->proto_defaults[i].protoName) == 0) return(i); return(-1); } /* ****************************************************** */ int ndpi_get_category_id(struct ndpi_detection_module_struct *ndpi_str, char *cat) { int i; for (i = 0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) { const char *name = ndpi_category_get_name(ndpi_str, i); if(strcasecmp(cat, name) == 0) return(i); } return(-1); } /* ****************************************************** */ void ndpi_dump_protocols(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) printf("%3d %-22s %-8s %-12s %s\n", i, ndpi_str->proto_defaults[i].protoName, ndpi_get_l4_proto_name(ndpi_get_l4_proto_info(ndpi_str, i)), ndpi_get_proto_breed_name(ndpi_str, ndpi_str->proto_defaults[i].protoBreed), ndpi_category_get_name(ndpi_str, ndpi_str->proto_defaults[i].protoCategory)); } /* ****************************************************** */ /* * Find the first occurrence of find in s, where the search is limited to the * first slen characters of s. */ char *ndpi_strnstr(const char *s, const char *find, size_t slen) { char c; size_t len; if((c = *find++) != '\0') { len = strnlen(find, slen); do { char sc; do { if(slen-- < 1 || (sc = *s++) == '\0') return(NULL); } while (sc != c); if(len > slen) return(NULL); } while (strncmp(s, find, len) != 0); s--; } return((char *) s); } /* ****************************************************** */ /* * Same as ndpi_strnstr but case-insensitive */ const char * ndpi_strncasestr(const char *str1, const char *str2, size_t len) { size_t str1_len = strnlen(str1, len); size_t str2_len = strlen(str2); size_t i; for(i = 0; i < (str1_len - str2_len + 1); i++){ if(str1[0] == '\0') return NULL; else if(strncasecmp(str1, str2, str2_len) == 0) return(str1); str1++; } return NULL; } /* ****************************************************** */ int ndpi_match_prefix(const u_int8_t *payload, size_t payload_len, const char *str, size_t str_len) { int rc = str_len <= payload_len ? memcmp(payload, str, str_len) == 0 : 0; return(rc); } /* ****************************************************** */ int ndpi_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int8_t is_host_match) { AC_TEXT_t ac_input_text; ndpi_automa *automa = is_host_match ? &ndpi_str->host_automa : &ndpi_str->content_automa; AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED}; int rc; if((automa->ac_automa == NULL) || (string_to_match_len == 0)) return(NDPI_PROTOCOL_UNKNOWN); if(!automa->ac_automa_finalized) { printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__); return(0); /* No matches */ } ac_input_text.astring = string_to_match, ac_input_text.length = string_to_match_len; rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; /* We need to take into account also rc == 0 that is used for partial matches */ ret_match->protocol_id = match.number, ret_match->protocol_category = match.category, ret_match->protocol_breed = match.breed; return(rc ? match.number : 0); } /* **************************************** */ static u_int8_t ndpi_is_more_generic_protocol(u_int16_t previous_proto, u_int16_t new_proto) { /* Sometimes certificates are more generic than previously identified protocols */ if((previous_proto == NDPI_PROTOCOL_UNKNOWN) || (previous_proto == new_proto)) return(0); switch (previous_proto) { case NDPI_PROTOCOL_WHATSAPP_CALL: case NDPI_PROTOCOL_WHATSAPP_FILES: if(new_proto == NDPI_PROTOCOL_WHATSAPP) return(1); } return(0); } /* ****************************************************** */ static u_int16_t ndpi_automa_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, u_int16_t master_protocol_id, ndpi_protocol_match_result *ret_match, u_int8_t is_host_match) { int matching_protocol_id; struct ndpi_packet_struct *packet = &flow->packet; matching_protocol_id = ndpi_match_string_subprotocol(ndpi_str, string_to_match, string_to_match_len, ret_match, is_host_match); #ifdef DEBUG { char m[256]; int len = ndpi_min(sizeof(m), string_to_match_len); strncpy(m, string_to_match, len); m[len] = '\0'; NDPI_LOG_DBG2(ndpi_str, "[NDPI] ndpi_match_host_subprotocol(%s): %s\n", m, ndpi_str->proto_defaults[matching_protocol_id].protoName); } #endif if((matching_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (!ndpi_is_more_generic_protocol(packet->detected_protocol_stack[0], matching_protocol_id))) { /* Move the protocol on slot 0 down one position */ packet->detected_protocol_stack[1] = master_protocol_id, packet->detected_protocol_stack[0] = matching_protocol_id; flow->detected_protocol_stack[0] = packet->detected_protocol_stack[0], flow->detected_protocol_stack[1] = packet->detected_protocol_stack[1]; if(flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) flow->category = ret_match->protocol_category; return(packet->detected_protocol_stack[0]); } #ifdef DEBUG string_to_match[string_to_match_len] = '\0'; NDPI_LOG_DBG2(ndpi_str, "[NTOP] Unable to find a match for '%s'\n", string_to_match); #endif ret_match->protocol_id = NDPI_PROTOCOL_UNKNOWN, ret_match->protocol_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, ret_match->protocol_breed = NDPI_PROTOCOL_UNRATED; return(NDPI_PROTOCOL_UNKNOWN); } /* ****************************************************** */ u_int16_t ndpi_match_host_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int16_t master_protocol_id) { u_int16_t rc = ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len, master_protocol_id, ret_match, 1); ndpi_protocol_category_t id = ret_match->protocol_category; if(ndpi_get_custom_category_match(ndpi_str, string_to_match, string_to_match_len, &id) != -1) { /* if(id != -1) */ { flow->category = ret_match->protocol_category = id; rc = master_protocol_id; } } return(rc); } /* **************************************** */ int ndpi_match_hostname_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t master_protocol, char *name, u_int name_len) { ndpi_protocol_match_result ret_match; u_int16_t subproto, what_len; char *what; if((name_len > 2) && (name[0] == '*') && (name[1] == '.')) what = &name[1], what_len = name_len - 1; else what = name, what_len = name_len; subproto = ndpi_match_host_subprotocol(ndpi_struct, flow, what, what_len, &ret_match, master_protocol); if(subproto != NDPI_PROTOCOL_UNKNOWN) { ndpi_set_detected_protocol(ndpi_struct, flow, subproto, master_protocol); ndpi_int_change_category(ndpi_struct, flow, ret_match.protocol_category); return(1); } else return(0); } /* ****************************************************** */ u_int16_t ndpi_match_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int16_t master_protocol_id) { return(ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len, master_protocol_id, ret_match, 0)); } /* ****************************************************** */ int ndpi_match_bigram(struct ndpi_detection_module_struct *ndpi_str, ndpi_automa *automa, char *bigram_to_match) { AC_TEXT_t ac_input_text; AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED}; int rc; if((automa->ac_automa == NULL) || (bigram_to_match == NULL)) return(-1); if(!automa->ac_automa_finalized) { #if 1 ndpi_finalize_initalization(ndpi_str); #else printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__); return(0); /* No matches */ #endif } ac_input_text.astring = bigram_to_match, ac_input_text.length = 2; rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; return(rc ? match.number : 0); } /* ****************************************************** */ void ndpi_free_flow(struct ndpi_flow_struct *flow) { if(flow) { if(flow->http.url) ndpi_free(flow->http.url); if(flow->http.content_type) ndpi_free(flow->http.content_type); if(flow->http.user_agent) ndpi_free(flow->http.user_agent); if(flow->kerberos_buf.pktbuf) ndpi_free(flow->kerberos_buf.pktbuf); if(flow_is_proto(flow, NDPI_PROTOCOL_TLS)) { if(flow->protos.stun_ssl.ssl.server_names) ndpi_free(flow->protos.stun_ssl.ssl.server_names); if(flow->protos.stun_ssl.ssl.alpn) ndpi_free(flow->protos.stun_ssl.ssl.alpn); if(flow->protos.stun_ssl.ssl.tls_supported_versions) ndpi_free(flow->protos.stun_ssl.ssl.tls_supported_versions); if(flow->protos.stun_ssl.ssl.issuerDN) ndpi_free(flow->protos.stun_ssl.ssl.issuerDN); if(flow->protos.stun_ssl.ssl.subjectDN) ndpi_free(flow->protos.stun_ssl.ssl.subjectDN); if(flow->l4.tcp.tls.srv_cert_fingerprint_ctx) ndpi_free(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) ndpi_free(flow->protos.stun_ssl.ssl.encrypted_sni.esni); } if(flow->l4_proto == IPPROTO_TCP) { if(flow->l4.tcp.tls.message.buffer) ndpi_free(flow->l4.tcp.tls.message.buffer); } ndpi_free(flow); } } /* ****************************************************** */ char *ndpi_revision() { return(NDPI_GIT_RELEASE); } /* ****************************************************** */ #ifdef WIN32 /* https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows */ int gettimeofday(struct timeval *tp, struct timezone *tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) // until 00:00:00 January 1, 1970 static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t) file_time.dwLowDateTime); time += ((uint64_t) file_time.dwHighDateTime) << 32; tp->tv_sec = (long) ((time - EPOCH) / 10000000L); tp->tv_usec = (long) (system_time.wMilliseconds * 1000); return(0); } #endif int NDPI_BITMASK_COMPARE(NDPI_PROTOCOL_BITMASK a, NDPI_PROTOCOL_BITMASK b) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) { if(a.fds_bits[i] & b.fds_bits[i]) return(1); } return(0); } #ifdef CODE_UNUSED int NDPI_BITMASK_IS_EMPTY(NDPI_PROTOCOL_BITMASK a) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) if(a.fds_bits[i] != 0) return(0); return(1); } void NDPI_DUMP_BITMASK(NDPI_PROTOCOL_BITMASK a) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) printf("[%d=%u]", i, a.fds_bits[i]); printf("\n"); } #endif u_int16_t ndpi_get_api_version() { return(NDPI_API_VERSION); } ndpi_proto_defaults_t *ndpi_get_proto_defaults(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->proto_defaults); } u_int ndpi_get_ndpi_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_supported_protocols); } u_int ndpi_get_ndpi_num_custom_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_custom_protocols); } u_int ndpi_get_ndpi_detection_module_size() { return(sizeof(struct ndpi_detection_module_struct)); } void ndpi_set_log_level(struct ndpi_detection_module_struct *ndpi_str, u_int l){ ndpi_str->ndpi_log_level = l; } /* ******************************************************************** */ /* LRU cache */ struct ndpi_lru_cache *ndpi_lru_cache_init(u_int32_t num_entries) { struct ndpi_lru_cache *c = (struct ndpi_lru_cache *) ndpi_malloc(sizeof(struct ndpi_lru_cache)); if(!c) return(NULL); c->entries = (struct ndpi_lru_cache_entry *) ndpi_calloc(num_entries, sizeof(struct ndpi_lru_cache_entry)); if(!c->entries) { ndpi_free(c); return(NULL); } else c->num_entries = num_entries; return(c); } void ndpi_lru_free_cache(struct ndpi_lru_cache *c) { ndpi_free(c->entries); ndpi_free(c); } u_int8_t ndpi_lru_find_cache(struct ndpi_lru_cache *c, u_int32_t key, u_int16_t *value, u_int8_t clean_key_when_found) { u_int32_t slot = key % c->num_entries; if(c->entries[slot].is_full) { *value = c->entries[slot].value; if(clean_key_when_found) c->entries[slot].is_full = 0; return(1); } else return(0); } void ndpi_lru_add_to_cache(struct ndpi_lru_cache *c, u_int32_t key, u_int16_t value) { u_int32_t slot = key % c->num_entries; c->entries[slot].is_full = 1, c->entries[slot].key = key, c->entries[slot].value = value; } /* ******************************************************************** */ /* This function tells if it's possible to further dissect a given flow 0 - All possible dissection has been completed 1 - Additional dissection is possible */ u_int8_t ndpi_extra_dissection_possible(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int16_t proto = flow->detected_protocol_stack[1] ? flow->detected_protocol_stack[1] : flow->detected_protocol_stack[0]; #if 0 printf("[DEBUG] %s(%u.%u): %u\n", __FUNCTION__, flow->detected_protocol_stack[0], flow->detected_protocol_stack[1], proto); #endif switch (proto) { case NDPI_PROTOCOL_TLS: if(!flow->l4.tcp.tls.certificate_processed) return(1); /* TODO: add check for TLS 1.3 */ break; case NDPI_PROTOCOL_HTTP: if((flow->host_server_name[0] == '\0') || (flow->http.response_status_code == 0)) return(1); break; case NDPI_PROTOCOL_DNS: if(flow->protos.dns.num_answers == 0) return(1); break; case NDPI_PROTOCOL_FTP_CONTROL: case NDPI_PROTOCOL_MAIL_POP: case NDPI_PROTOCOL_MAIL_IMAP: case NDPI_PROTOCOL_MAIL_SMTP: if(flow->protos.ftp_imap_pop_smtp.password[0] == '\0') return(1); break; case NDPI_PROTOCOL_SSH: if((flow->protos.ssh.hassh_client[0] == '\0') || (flow->protos.ssh.hassh_server[0] == '\0')) return(1); break; case NDPI_PROTOCOL_TELNET: if(!flow->protos.telnet.password_detected) return(1); break; } return(0); } /* ******************************************************************** */ const char *ndpi_get_l4_proto_name(ndpi_l4_proto_info proto) { switch (proto) { case ndpi_l4_proto_unknown: return(""); break; case ndpi_l4_proto_tcp_only: return("TCP"); break; case ndpi_l4_proto_udp_only: return("UDP"); break; case ndpi_l4_proto_tcp_and_udp: return("TCP/UDP"); break; } return(""); } /* ******************************************************************** */ ndpi_l4_proto_info ndpi_get_l4_proto_info(struct ndpi_detection_module_struct *ndpi_struct, u_int16_t ndpi_proto_id) { if(ndpi_proto_id < ndpi_struct->ndpi_num_supported_protocols) { u_int16_t idx = ndpi_struct->proto_defaults[ndpi_proto_id].protoIdx; NDPI_SELECTION_BITMASK_PROTOCOL_SIZE bm = ndpi_struct->callback_buffer[idx].ndpi_selection_bitmask; if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP) return(ndpi_l4_proto_tcp_only); else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP) return(ndpi_l4_proto_udp_only); else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP) return(ndpi_l4_proto_tcp_and_udp); } return(ndpi_l4_proto_unknown); /* default */ } /* ******************************************************************** */ ndpi_ptree_t *ndpi_ptree_create(void) { ndpi_ptree_t *tree = (ndpi_ptree_t *) ndpi_malloc(sizeof(ndpi_ptree_t)); if(tree) { tree->v4 = ndpi_New_Patricia(32); tree->v6 = ndpi_New_Patricia(128); if((!tree->v4) || (!tree->v6)) { ndpi_ptree_destroy(tree); return(NULL); } } return(tree); } /* ******************************************************************** */ void ndpi_ptree_destroy(ndpi_ptree_t *tree) { if(tree) { if(tree->v4) ndpi_Destroy_Patricia(tree->v4, free_ptree_data); if(tree->v6) ndpi_Destroy_Patricia(tree->v6, free_ptree_data); ndpi_free(tree); } } /* ******************************************************************** */ int ndpi_ptree_insert(ndpi_ptree_t *tree, const ndpi_ip_addr_t *addr, u_int8_t bits, uint user_data) { u_int8_t is_v6 = ndpi_is_ipv6(addr); patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4; prefix_t prefix; patricia_node_t *node; if(bits > ptree->maxbits) return(-1); if(is_v6) fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits); else fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits); /* Verify that the node does not already exist */ node = ndpi_patricia_search_best(ptree, &prefix); if(node && (node->prefix->bitlen == bits)) return(-2); node = ndpi_patricia_lookup(ptree, &prefix); if(node != NULL) { node->value.uv.user_value = user_data, node->value.uv.additional_user_value = 0; return(0); } return(-3); } /* ******************************************************************** */ int ndpi_ptree_match_addr(ndpi_ptree_t *tree, const ndpi_ip_addr_t *addr, uint *user_data) { u_int8_t is_v6 = ndpi_is_ipv6(addr); patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4; prefix_t prefix; patricia_node_t *node; int bits = ptree->maxbits; if(is_v6) fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits); else fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits); node = ndpi_patricia_search_best(ptree, &prefix); if(node) { *user_data = node->value.uv.user_value; return(0); } return(-1); } /* ******************************************************************** */ void ndpi_md5(const u_char *data, size_t data_len, u_char hash[16]) { ndpi_MD5_CTX ctx; ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, data, data_len); ndpi_MD5Final(hash, &ctx); } /* ******************************************************************** */ static int enough(int a, int b) { u_int8_t percentage = 20; if(b == 0) return(0); if(a == 0) return(1); if(b > (((a+1)*percentage)/100)) return(1); return(0); } /* ******************************************************************** */ // #define DGA_DEBUG 1 int ndpi_check_dga_name(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *name) { int len, rc = 0; len = strlen(name); if(len >= 5) { int i, j, num_found = 0, num_impossible = 0, num_bigram_checks = 0, num_digits = 0, num_vowels = 0, num_words = 0; char tmp[128], *word, *tok_tmp; len = snprintf(tmp, sizeof(tmp)-1, "%s", name); if(len < 0) return(0); for(i=0, j=0; (i<len) && (j<(sizeof(tmp)-1)); i++) { tmp[j++] = tolower(name[i]); } tmp[j] = '\0'; len = j; for(word = strtok_r(tmp, ".", &tok_tmp); ; word = strtok_r(NULL, ".", &tok_tmp)) { if(!word) break; num_words++; if(strlen(word) < 3) continue; #ifdef DGA_DEBUG printf("-> %s [%s][len: %u]\n", word, name, (unsigned int)strlen(word)); #endif for(i = 0; word[i+1] != '\0'; i++) { if(isdigit(word[i])) { num_digits++; // if(!isdigit(word[i+1])) num_impossible++; continue; } switch(word[i]) { case '_': case '-': case ':': continue; break; case '.': continue; break; } switch(word[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': num_vowels++; break; } if(isdigit(word[i+1])) { num_digits++; // num_impossible++; continue; } num_bigram_checks++; if(ndpi_match_bigram(ndpi_str, &ndpi_str->bigrams_automa, &word[i])) { num_found++; } else { if(ndpi_match_bigram(ndpi_str, &ndpi_str->impossible_bigrams_automa, &word[i])) { #ifdef DGA_DEBUG printf("IMPOSSIBLE %s\n", &word[i]); #endif num_impossible++; } } } /* for */ } /* for */ #ifdef DGA_DEBUG printf("[num_found: %u][num_impossible: %u][num_digits: %u][num_bigram_checks: %u][num_vowels: %u/%u]\n", num_found, num_impossible, num_digits, num_bigram_checks, num_vowels, j-num_vowels); #endif if(num_bigram_checks && ((num_found == 0) || ((num_digits > 5) && (num_words <= 3)) || enough(num_found, num_impossible))) rc = 1; if(rc && flow) NDPI_SET_BIT(flow->risk, NDPI_SUSPICIOUS_DGA_DOMAIN); #ifdef DGA_DEBUG if(rc) printf("DGA %s [num_found: %u][num_impossible: %u]\n", name, num_found, num_impossible); #endif } return(rc); }
/* * ndpi_main.c * * Copyright (C) 2011-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include <stdlib.h> #include <errno.h> #include <sys/types.h> #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_UNKNOWN #include "ndpi_config.h" #include "ndpi_api.h" #include "ahocorasick.h" #include "libcache.h" #include <time.h> #ifndef WIN32 #include <unistd.h> #endif #if defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ #include <sys/endian.h> #endif #include "ndpi_content_match.c.inc" #include "third_party/include/ndpi_patricia.h" #include "third_party/include/ht_hash.h" #include "third_party/include/ndpi_md5.h" /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static int _ndpi_debug_callbacks = 0; /* #define MATCH_DEBUG 1 */ /* ****************************************** */ static void *(*_ndpi_flow_malloc)(size_t size); static void (*_ndpi_flow_free)(void *ptr); static void *(*_ndpi_malloc)(size_t size); static void (*_ndpi_free)(void *ptr); /* ****************************************** */ /* Forward */ static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range, ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root, const char *_func, int _line); static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root); /* ****************************************** */ static inline uint8_t flow_is_proto(struct ndpi_flow_struct *flow, u_int16_t p) { return((flow->detected_protocol_stack[0] == p) || (flow->detected_protocol_stack[1] == p)); } /* ****************************************** */ void *ndpi_malloc(size_t size) { return(_ndpi_malloc ? _ndpi_malloc(size) : malloc(size)); } void *ndpi_flow_malloc(size_t size) { return(_ndpi_flow_malloc ? _ndpi_flow_malloc(size) : ndpi_malloc(size)); } /* ****************************************** */ void *ndpi_calloc(unsigned long count, size_t size) { size_t len = count * size; void *p = ndpi_malloc(len); if(p) memset(p, 0, len); return(p); } /* ****************************************** */ void ndpi_free(void *ptr) { if(_ndpi_free) _ndpi_free(ptr); else free(ptr); } /* ****************************************** */ void ndpi_flow_free(void *ptr) { if(_ndpi_flow_free) _ndpi_flow_free(ptr); else ndpi_free_flow((struct ndpi_flow_struct *) ptr); } /* ****************************************** */ void *ndpi_realloc(void *ptr, size_t old_size, size_t new_size) { void *ret = ndpi_malloc(new_size); if(!ret) return(ret); else { memcpy(ret, ptr, old_size); ndpi_free(ptr); return(ret); } } /* ****************************************** */ char *ndpi_strdup(const char *s) { if(s == NULL ){ return NULL; } int len = strlen(s); char *m = ndpi_malloc(len + 1); if(m) { memcpy(m, s, len); m[len] = '\0'; } return(m); } /* *********************************************************************************** */ /* Opaque structure defined here */ struct ndpi_ptree { patricia_tree_t *v4; patricia_tree_t *v6; }; /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_struct(void) { return(sizeof(struct ndpi_flow_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_id_struct(void) { return(sizeof(struct ndpi_id_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_tcp_struct(void) { return(sizeof(struct ndpi_flow_tcp_struct)); } /* *********************************************************************************** */ u_int32_t ndpi_detection_get_sizeof_ndpi_flow_udp_struct(void) { return(sizeof(struct ndpi_flow_udp_struct)); } /* *********************************************************************************** */ char *ndpi_get_proto_by_id(struct ndpi_detection_module_struct *ndpi_str, u_int id) { return((id >= ndpi_str->ndpi_num_supported_protocols) ? NULL : ndpi_str->proto_defaults[id].protoName); } /* *********************************************************************************** */ u_int16_t ndpi_get_proto_by_name(struct ndpi_detection_module_struct *ndpi_str, const char *name) { u_int16_t i, num = ndpi_get_num_supported_protocols(ndpi_str); for (i = 0; i < num; i++) if(strcasecmp(ndpi_get_proto_by_id(ndpi_str, i), name) == 0) return(i); return(NDPI_PROTOCOL_UNKNOWN); } /* ************************************************************************************* */ #ifdef CODE_UNUSED ndpi_port_range *ndpi_build_default_ports_range(ndpi_port_range *ports, u_int16_t portA_low, u_int16_t portA_high, u_int16_t portB_low, u_int16_t portB_high, u_int16_t portC_low, u_int16_t portC_high, u_int16_t portD_low, u_int16_t portD_high, u_int16_t portE_low, u_int16_t portE_high) { int i = 0; ports[i].port_low = portA_low, ports[i].port_high = portA_high; i++; ports[i].port_low = portB_low, ports[i].port_high = portB_high; i++; ports[i].port_low = portC_low, ports[i].port_high = portC_high; i++; ports[i].port_low = portD_low, ports[i].port_high = portD_high; i++; ports[i].port_low = portE_low, ports[i].port_high = portE_high; return(ports); } #endif /* *********************************************************************************** */ ndpi_port_range *ndpi_build_default_ports(ndpi_port_range *ports, u_int16_t portA, u_int16_t portB, u_int16_t portC, u_int16_t portD, u_int16_t portE) { int i = 0; ports[i].port_low = portA, ports[i].port_high = portA; i++; ports[i].port_low = portB, ports[i].port_high = portB; i++; ports[i].port_low = portC, ports[i].port_high = portC; i++; ports[i].port_low = portD, ports[i].port_high = portD; i++; ports[i].port_low = portE, ports[i].port_high = portE; return(ports); } /* ********************************************************************************** */ void ndpi_set_proto_breed(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId, ndpi_protocol_breed_t breed) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return; else ndpi_str->proto_defaults[protoId].protoBreed = breed; } /* ********************************************************************************** */ void ndpi_set_proto_category(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId, ndpi_protocol_category_t protoCategory) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return; else ndpi_str->proto_defaults[protoId].protoCategory = protoCategory; } /* ********************************************************************************** */ /* There are some (master) protocols that are informative, meaning that it shows what is the subprotocol about, but also that the subprotocol isn't a real protocol. Example: - DNS is informative as if we see a DNS request for www.facebook.com, the returned protocol is DNS.Facebook, but Facebook isn't a real subprotocol but rather it indicates a query for Facebook and not Facebook traffic. - HTTP/SSL are NOT informative as SSL.Facebook (likely) means that this is SSL (HTTPS) traffic containg Facebook traffic. */ u_int8_t ndpi_is_subprotocol_informative(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId) { if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) return(0); switch (protoId) { /* All dissectors that have calls to ndpi_match_host_subprotocol() */ case NDPI_PROTOCOL_DNS: return(1); break; default: return(0); } } /* ********************************************************************************** */ void ndpi_exclude_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t protocol_id, const char *_file, const char *_func, int _line) { if(protocol_id < NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES if(ndpi_str && ndpi_str->ndpi_log_level >= NDPI_LOG_DEBUG && ndpi_str->ndpi_debug_printf != NULL) { (*(ndpi_str->ndpi_debug_printf))(protocol_id, ndpi_str, NDPI_LOG_DEBUG, _file, _func, _line, "exclude %s\n", ndpi_get_proto_name(ndpi_str, protocol_id)); } #endif NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, protocol_id); } } /* ********************************************************************************** */ void ndpi_set_proto_defaults(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_breed_t breed, u_int16_t protoId, u_int8_t can_have_a_subprotocol, u_int16_t tcp_master_protoId[2], u_int16_t udp_master_protoId[2], char *protoName, ndpi_protocol_category_t protoCategory, ndpi_port_range *tcpDefPorts, ndpi_port_range *udpDefPorts) { char *name; int j; if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) { #ifdef DEBUG NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: INTERNAL ERROR\n", protoName, protoId); #endif return; } if(ndpi_str->proto_defaults[protoId].protoName != NULL) { #ifdef DEBUG NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: already initialized. Ignoring it\n", protoName, protoId); #endif return; } name = ndpi_strdup(protoName); if(ndpi_str->proto_defaults[protoId].protoName) ndpi_free(ndpi_str->proto_defaults[protoId].protoName); ndpi_str->proto_defaults[protoId].protoName = name, ndpi_str->proto_defaults[protoId].protoCategory = protoCategory, ndpi_str->proto_defaults[protoId].protoId = protoId, ndpi_str->proto_defaults[protoId].protoBreed = breed; ndpi_str->proto_defaults[protoId].can_have_a_subprotocol = can_have_a_subprotocol; memcpy(&ndpi_str->proto_defaults[protoId].master_tcp_protoId, tcp_master_protoId, 2 * sizeof(u_int16_t)); memcpy(&ndpi_str->proto_defaults[protoId].master_udp_protoId, udp_master_protoId, 2 * sizeof(u_int16_t)); for (j = 0; j < MAX_DEFAULT_PORTS; j++) { if(udpDefPorts[j].port_low != 0) addDefaultPort(ndpi_str, &udpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->udpRoot, __FUNCTION__, __LINE__); if(tcpDefPorts[j].port_low != 0) addDefaultPort(ndpi_str, &tcpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->tcpRoot, __FUNCTION__, __LINE__); /* No port range, just the lower port */ ndpi_str->proto_defaults[protoId].tcp_default_ports[j] = tcpDefPorts[j].port_low; ndpi_str->proto_defaults[protoId].udp_default_ports[j] = udpDefPorts[j].port_low; } } /* ******************************************************************** */ static int ndpi_default_ports_tree_node_t_cmp(const void *a, const void *b) { ndpi_default_ports_tree_node_t *fa = (ndpi_default_ports_tree_node_t *) a; ndpi_default_ports_tree_node_t *fb = (ndpi_default_ports_tree_node_t *) b; //printf("[NDPI] %s(%d, %d)\n", __FUNCTION__, fa->default_port, fb->default_port); return((fa->default_port == fb->default_port) ? 0 : ((fa->default_port < fb->default_port) ? -1 : 1)); } /* ******************************************************************** */ void ndpi_default_ports_tree_node_t_walker(const void *node, const ndpi_VISIT which, const int depth) { ndpi_default_ports_tree_node_t *f = *(ndpi_default_ports_tree_node_t **) node; printf("<%d>Walk on node %s (%u)\n", depth, which == ndpi_preorder ? "ndpi_preorder" : which == ndpi_postorder ? "ndpi_postorder" : which == ndpi_endorder ? "ndpi_endorder" : which == ndpi_leaf ? "ndpi_leaf" : "unknown", f->default_port); } /* ******************************************************************** */ static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range, ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root, const char *_func, int _line) { u_int16_t port; for (port = range->port_low; port <= range->port_high; port++) { ndpi_default_ports_tree_node_t *node = (ndpi_default_ports_tree_node_t *) ndpi_malloc(sizeof(ndpi_default_ports_tree_node_t)); ndpi_default_ports_tree_node_t *ret; if(!node) { NDPI_LOG_ERR(ndpi_str, "%s:%d not enough memory\n", _func, _line); break; } node->proto = def, node->default_port = port, node->customUserProto = customUserProto; ret = (ndpi_default_ports_tree_node_t *) ndpi_tsearch(node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */ if(ret != node) { NDPI_LOG_DBG(ndpi_str, "[NDPI] %s:%d found duplicate for port %u: overwriting it with new value\n", _func, _line, port); ret->proto = def; ndpi_free(node); } } } /* ****************************************************** */ /* NOTE This function must be called with a semaphore set, this in order to avoid changing the datastructures while using them */ static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root) { ndpi_default_ports_tree_node_t node; u_int16_t port; for (port = range->port_low; port <= range->port_high; port++) { ndpi_default_ports_tree_node_t *ret; node.proto = def, node.default_port = port; ret = (ndpi_default_ports_tree_node_t *) ndpi_tdelete( &node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */ if(ret != NULL) { ndpi_free((ndpi_default_ports_tree_node_t *) ret); return(0); } } return(-1); } /* ****************************************************** */ static int ndpi_string_to_automa(struct ndpi_detection_module_struct *ndpi_str, ndpi_automa *automa, char *value, u_int16_t protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed, u_int8_t free_str_on_duplicate) { AC_PATTERN_t ac_pattern; AC_ERROR_t rc; if((value == NULL) || (protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS))) { NDPI_LOG_ERR(ndpi_str, "[NDPI] protoId=%d: INTERNAL ERROR\n", protocol_id); return(-1); } if(automa->ac_automa == NULL) return(-2); ac_pattern.astring = value, ac_pattern.rep.number = protocol_id, ac_pattern.rep.category = (u_int16_t) category, ac_pattern.rep.breed = (u_int16_t) breed; #ifdef MATCH_DEBUG printf("Adding to automa [%s][protocol_id: %u][category: %u][breed: %u]\n", value, protocol_id, category, breed); #endif if(value == NULL) ac_pattern.length = 0; else ac_pattern.length = strlen(ac_pattern.astring); rc = ac_automata_add(((AC_AUTOMATA_t *) automa->ac_automa), &ac_pattern); if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS) return(-2); if(rc == ACERR_DUPLICATE_PATTERN && free_str_on_duplicate) ndpi_free(value); return(0); } /* ****************************************************** */ static int ndpi_add_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *_value, int protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) { int rv; char *value = ndpi_strdup(_value); if(!value) return(-1); #ifdef DEBUG NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding [%s][%d]\n", value, protocol_id); #endif rv = ndpi_string_to_automa(ndpi_str, &ndpi_str->host_automa, value, protocol_id, category, breed, 1); if(rv != 0) ndpi_free(value); return(rv); } /* ****************************************************** */ #ifdef CODE_UNUSED int ndpi_add_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) { return(ndpi_string_to_automa(ndpi_str, &ndpi_str->content_automa, value, protocol_id, category, breed, 0)); } #endif /* ****************************************************** */ /* NOTE This function must be called with a semaphore set, this in order to avoid changing the datastructures while using them */ static int ndpi_remove_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id) { NDPI_LOG_ERR(ndpi_str, "[NDPI] Missing implementation for proto %s/%d\n", value, protocol_id); return(-1); } /* ******************************************************************** */ void ndpi_init_protocol_match(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_match *match) { u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}; ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; if(ndpi_str->proto_defaults[match->protocol_id].protoName == NULL) { ndpi_str->proto_defaults[match->protocol_id].protoName = ndpi_strdup(match->proto_name); ndpi_str->proto_defaults[match->protocol_id].protoId = match->protocol_id; ndpi_str->proto_defaults[match->protocol_id].protoCategory = match->protocol_category; ndpi_str->proto_defaults[match->protocol_id].protoBreed = match->protocol_breed; ndpi_set_proto_defaults(ndpi_str, ndpi_str->proto_defaults[match->protocol_id].protoBreed, ndpi_str->proto_defaults[match->protocol_id].protoId, 0 /* can_have_a_subprotocol */, no_master, no_master, ndpi_str->proto_defaults[match->protocol_id].protoName, ndpi_str->proto_defaults[match->protocol_id].protoCategory, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); } ndpi_add_host_url_subprotocol(ndpi_str, match->string_to_match, match->protocol_id, match->protocol_category, match->protocol_breed); } /* ******************************************************************** */ /* Self check function to be called onli for testing purposes */ void ndpi_self_check_host_match() { u_int32_t i, j; for (i = 0; host_match[i].string_to_match != NULL; i++) { for (j = 0; host_match[j].string_to_match != NULL; j++) { if((i != j) && (strcmp(host_match[i].string_to_match, host_match[j].string_to_match) == 0)) { printf("[INTERNAL ERROR]: Duplicate string detected '%s' [id: %u, id %u]\n", host_match[i].string_to_match, i, j); printf("\nPlease fix host_match[] in ndpi_content_match.c.inc\n"); exit(0); } } } } /* ******************************************************************** */ static void init_string_based_protocols(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; host_match[i].string_to_match != NULL; i++) ndpi_init_protocol_match(ndpi_str, &host_match[i]); ndpi_enable_loaded_categories(ndpi_str); #ifdef MATCH_DEBUG // ac_automata_display(ndpi_str->host_automa.ac_automa, 'n'); #endif #if 1 for (i = 0; ndpi_en_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->bigrams_automa, (char *) ndpi_en_bigrams[i], 1, 1, 1, 0); #else for (i = 0; ndpi_en_popular_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->bigrams_automa, (char *) ndpi_en_popular_bigrams[i], 1, 1, 1, 0); #endif for (i = 0; ndpi_en_impossible_bigrams[i] != NULL; i++) ndpi_string_to_automa(ndpi_str, &ndpi_str->impossible_bigrams_automa, (char *) ndpi_en_impossible_bigrams[i], 1, 1, 1, 0); } /* ******************************************************************** */ int ndpi_set_detection_preferences(struct ndpi_detection_module_struct *ndpi_str, ndpi_detection_preference pref, int value) { switch (pref) { case ndpi_pref_direction_detect_disable: ndpi_str->direction_detect_disable = (u_int8_t) value; break; default: return(-1); } return(0); } /* ******************************************************************** */ static void ndpi_validate_protocol_initialization(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) { if(ndpi_str->proto_defaults[i].protoName == NULL) { NDPI_LOG_ERR(ndpi_str, "[NDPI] INTERNAL ERROR missing protoName initialization for [protoId=%d]: recovering\n", i); } else { if((i != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[i].protoCategory == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) { NDPI_LOG_ERR(ndpi_str, "[NDPI] INTERNAL ERROR missing category [protoId=%d/%s] initialization: recovering\n", i, ndpi_str->proto_defaults[i].protoName ? ndpi_str->proto_defaults[i].protoName : "???"); } } } } /* ******************************************************************** */ /* This function is used to map protocol name and default ports and it MUST be updated whenever a new protocol is added to NDPI. Do NOT add web services (NDPI_SERVICE_xxx) here. */ static void ndpi_init_protocol_defaults(struct ndpi_detection_module_struct *ndpi_str) { ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}, custom_master[2]; /* Reset all settings */ memset(ndpi_str->proto_defaults, 0, sizeof(ndpi_str->proto_defaults)); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNRATED, NDPI_PROTOCOL_UNKNOWN, 0 /* can_have_a_subprotocol */, no_master, no_master, "Unknown", NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_FTP_CONTROL, 0 /* can_have_a_subprotocol */, no_master, no_master, "FTP_CONTROL", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 21, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FTP_DATA, 0 /* can_have_a_subprotocol */, no_master, no_master, "FTP_DATA", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 20, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_POP, 0 /* can_have_a_subprotocol */, no_master, no_master, "POP3", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 110, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_POPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "POPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 995, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MAIL_SMTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMTP", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 25, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_SMTPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMTPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 465, 587, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_IMAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMAP", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 143, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_IMAPS, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMAPS", NDPI_PROTOCOL_CATEGORY_MAIL, ndpi_build_default_ports(ports_a, 993, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNS, 1 /* can_have_a_subprotocol */, no_master, no_master, "DNS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 53, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 53, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IPP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IMO, 0 /* can_have_a_subprotocol */, no_master, no_master, "IMO", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 80, 0 /* ntop */, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MDNS, 1 /* can_have_a_subprotocol */, no_master, no_master, "MDNS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5353, 5354, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "NTP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 123, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETBIOS, 0 /* can_have_a_subprotocol */, no_master, no_master, "NetBIOS", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 139, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 137, 138, 139, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NFS, 0 /* can_have_a_subprotocol */, no_master, no_master, "NFS", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 2049, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2049, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSDP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SSDP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BGP, 0 /* can_have_a_subprotocol */, no_master, no_master, "BGP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 179, 2605, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SNMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SNMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 161, 162, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_XDMCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "XDMCP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 177, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 177, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_DANGEROUS, NDPI_PROTOCOL_SMBV1, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMBv1", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SYSLOG, 0 /* can_have_a_subprotocol */, no_master, no_master, "Syslog", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 514, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 514, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "DHCP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 67, 68, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_POSTGRES, 0 /* can_have_a_subprotocol */, no_master, no_master, "PostgreSQL", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 5432, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MYSQL, 0 /* can_have_a_subprotocol */, no_master, no_master, "MySQL", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 3306, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECT_DOWNLOAD_LINK, 0 /* can_have_a_subprotocol */, no_master, no_master, "Direct_Download_Link", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_APPLEJUICE, 0 /* can_have_a_subprotocol */, no_master, no_master, "AppleJuice", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECTCONNECT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DirectConnect", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NATS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Nats", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_NTOP, 0 /* can_have_a_subprotocol */, no_master, no_master, "ntop", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VMWARE, 0 /* can_have_a_subprotocol */, no_master, no_master, "VMware", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 903, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 902, 903, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FBZERO, 0 /* can_have_a_subprotocol */, no_master, no_master, "FacebookZero", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_KONTIKI, 0 /* can_have_a_subprotocol */, no_master, no_master, "Kontiki", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_OPENFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "OpenFT", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_FASTTRACK, 0 /* can_have_a_subprotocol */, no_master, no_master, "FastTrack", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_GNUTELLA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Gnutella", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_EDONKEY, 0 /* can_have_a_subprotocol */, no_master, no_master, "eDonkey", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_BITTORRENT, 0 /* can_have_a_subprotocol */, no_master, no_master, "BitTorrent", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 51413, 53646, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6771, 51413, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Skype", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE_CALL, 0 /* can_have_a_subprotocol */, no_master, no_master, "SkypeCall", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TIKTOK, 0 /* can_have_a_subprotocol */, no_master, no_master, "TikTok", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEREDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Teredo", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3544, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WECHAT, 0 /* can_have_a_subprotocol */, no_master, /* wechat.com */ no_master, "WeChat", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEMCACHED, 0 /* can_have_a_subprotocol */, no_master, no_master, "Memcached", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 11211, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 11211, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMBV23, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMBv23", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MINING, 0 /* can_have_a_subprotocol */, no_master, no_master, "Mining", CUSTOM_CATEGORY_MINING, ndpi_build_default_ports(ports_a, 8333, 30303, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NEST_LOG_SINK, 0 /* can_have_a_subprotocol */, no_master, no_master, "NestLogSink", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 11095, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MODBUS, 1 /* no subprotocol */, no_master, no_master, "Modbus", NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */ ndpi_build_default_ports(ports_a, 502, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_CALL, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppCall", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DATASAVER, 0 /* can_have_a_subprotocol */, no_master, no_master, "DataSaver", NDPI_PROTOCOL_CATEGORY_WEB /* dummy */, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SIGNAL, 0 /* can_have_a_subprotocol */, no_master, /* https://signal.org */ no_master, "Signal", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOH_DOT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DoH_DoT", NDPI_PROTOCOL_CATEGORY_NETWORK /* dummy */, ndpi_build_default_ports(ports_a, 853, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_205, 0 /* can_have_a_subprotocol */, no_master, no_master, "FREE_205", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WIREGUARD, 0 /* can_have_a_subprotocol */, no_master, no_master, "WireGuard", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 51820, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_XBOX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Xbox", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 3074, 3076, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3074, 3076, 500, 3544, 4500) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PLAYSTATION, 0 /* can_have_a_subprotocol */, no_master, no_master, "Playstation", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1935, 3478, 3479, 3480, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3478, 3479, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "QQ", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_RTSP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTSP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 554, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 554, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ICECAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "IceCast", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPLIVE, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPLive", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ZATTOO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Zattoo", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SHOUTCAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "ShoutCast", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOPCAST, 0 /* can_have_a_subprotocol */, no_master, no_master, "Sopcast", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_58, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free58", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVUPLAYER, 0 /* can_have_a_subprotocol */, no_master, no_master, "TVUplayer", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_DOWNLOAD, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Download", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQLIVE, 0 /* can_have_a_subprotocol */, no_master, no_master, "QQLive", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_THUNDER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Thunder", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOULSEEK, 0 /* can_have_a_subprotocol */, no_master, no_master, "Soulseek", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PS_VUE, 0 /* can_have_a_subprotocol */, no_master, no_master, "PS_VUE", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_IRC, 0 /* can_have_a_subprotocol */, no_master, no_master, "IRC", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 194, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 194, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AYIYA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Ayiya", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5072, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UNENCRYPTED_JABBER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Unencrypted_Jabber", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FREE_69, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free69", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_71, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free71", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_VRRP, 0 /* can_have_a_subprotocol */, no_master, no_master, "VRRP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STEAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Steam", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HALFLIFE2, 0 /* can_have_a_subprotocol */, no_master, no_master, "HalfLife2", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLDOFWARCRAFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "WorldOfWarcraft", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_HOTSPOT_SHIELD, 0 /* can_have_a_subprotocol */, no_master, no_master, "HotspotShield", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_TELNET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Telnet", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 23, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); custom_master[0] = NDPI_PROTOCOL_SIP, custom_master[1] = NDPI_PROTOCOL_H323; ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_STUN, 0 /* can_have_a_subprotocol */, no_master, custom_master, "STUN", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3478, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_IP_IPSEC, 0 /* can_have_a_subprotocol */, no_master, no_master, "IPsec", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 500, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 500, 4500, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_GRE, 0 /* can_have_a_subprotocol */, no_master, no_master, "GRE", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "ICMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IGMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IGMP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_EGP, 0 /* can_have_a_subprotocol */, no_master, no_master, "EGP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_SCTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SCTP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_OSPF, 0 /* can_have_a_subprotocol */, no_master, no_master, "OSPF", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 2604, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IP_IN_IP, 0 /* can_have_a_subprotocol */, no_master, no_master, "IP_in_IP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RDP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RDP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 3389, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 3389, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VNC, 0 /* can_have_a_subprotocol */, no_master, no_master, "VNC", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FREE90, 0 /* can_have_a_subprotocol */, no_master, no_master, "Free90", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZOOM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Zoom", NDPI_PROTOCOL_CATEGORY_VIDEO, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_FILES, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppFiles", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsApp", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_TLS, 1 /* can_have_a_subprotocol */, no_master, no_master, "TLS", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSH, 0 /* can_have_a_subprotocol */, no_master, no_master, "SSH", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 22, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_USENET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Usenet", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MGCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "MGCP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IAX, 0 /* can_have_a_subprotocol */, no_master, no_master, "IAX", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 4569, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 4569, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AFP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AFP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 548, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 548, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HULU, 0 /* can_have_a_subprotocol */, no_master, no_master, "Hulu", NDPI_PROTOCOL_CATEGORY_STREAMING, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CHECKMK, 0 /* can_have_a_subprotocol */, no_master, no_master, "CHECKMK", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 6556, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_STEALTHNET, 0 /* can_have_a_subprotocol */, no_master, no_master, "Stealthnet", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_AIMINI, 0 /* can_have_a_subprotocol */, no_master, no_master, "Aimini", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SIP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SIP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 5060, 5061, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5060, 5061, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TRUPHONE, 0 /* can_have_a_subprotocol */, no_master, no_master, "TruPhone", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMPV6, 0 /* can_have_a_subprotocol */, no_master, no_master, "ICMPV6", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCPV6, 0 /* can_have_a_subprotocol */, no_master, no_master, "DHCPV6", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ARMAGETRON, 0 /* can_have_a_subprotocol */, no_master, no_master, "Armagetron", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CROSSFIRE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Crossfire", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOFUS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Dofus", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FIESTA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Fiesta", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FLORENSIA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Florensia", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_GUILDWARS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Guildwars", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_ACTIVESYNC, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_ActiveSync", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KERBEROS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Kerberos", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 88, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 88, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LDAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "LDAP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 389, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 389, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MAPLESTORY, 0 /* can_have_a_subprotocol */, no_master, no_master, "MapleStory", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MSSQL_TDS, 0 /* can_have_a_subprotocol */, no_master, no_master, "MsSQL-TDS", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1433, 1434, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PPTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "PPTP", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WARCRAFT3, 0 /* can_have_a_subprotocol */, no_master, no_master, "Warcraft3", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLD_OF_KUNG_FU, 0 /* can_have_a_subprotocol */, no_master, no_master, "WorldOfKungFu", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DCERPC, 0 /* can_have_a_subprotocol */, no_master, no_master, "DCE_RPC", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 135, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETFLOW, 0 /* can_have_a_subprotocol */, no_master, no_master, "NetFlow", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2055, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SFLOW, 0 /* can_have_a_subprotocol */, no_master, no_master, "sFlow", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6343, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_CONNECT, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Connect", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_PROXY, 1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Proxy", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8080, 3128, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CITRIX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Citrix", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1494, 2598, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBEX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Webex", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RADIUS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Radius", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1812, 1813, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1812, 1813, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMVIEWER, 0 /* can_have_a_subprotocol */, no_master, no_master, "TeamViewer", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 5938, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5938, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LOTUS_NOTES, 0 /* can_have_a_subprotocol */, no_master, no_master, "LotusNotes", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 1352, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SAP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3201, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_GTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "GTP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 2152, 2123, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UPNP, 0 /* can_have_a_subprotocol */, no_master, no_master, "UPnP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 1780, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1900, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TELEGRAM, 0 /* can_have_a_subprotocol */, no_master, no_master, "Telegram", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_QUIC, 1 /* can_have_a_subprotocol */, no_master, no_master, "QUIC", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 443, 80, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DIAMETER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Diameter", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3868, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_APPLE_PUSH, 0 /* can_have_a_subprotocol */, no_master, no_master, "ApplePush", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DROPBOX, 0 /* can_have_a_subprotocol */, no_master, no_master, "Dropbox", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 17500, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SPOTIFY, 0 /* can_have_a_subprotocol */, no_master, no_master, "Spotify", NDPI_PROTOCOL_CATEGORY_MUSIC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MESSENGER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Messenger", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LISP, 0 /* can_have_a_subprotocol */, no_master, no_master, "LISP", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 4342, 4341, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_EAQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "EAQ", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6000, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KAKAOTALK_VOICE, 0 /* can_have_a_subprotocol */, no_master, no_master, "KakaoTalk_Voice", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MPEGTS, 0 /* can_have_a_subprotocol */, no_master, no_master, "MPEG_TS", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); /* http://en.wikipedia.org/wiki/Link-local_Multicast_Name_Resolution */ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LLMNR, 0 /* can_have_a_subprotocol */, no_master, no_master, "LLMNR", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5355, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5355, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_REMOTE_SCAN, 0 /* can_have_a_subprotocol */, no_master, no_master, "RemoteScan", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 6077, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 6078, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_H323, 0 /* can_have_a_subprotocol */, no_master, no_master, "H323", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 1719, 1720, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1719, 1720, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OPENVPN, 0 /* can_have_a_subprotocol */, no_master, no_master, "OpenVPN", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 1194, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 1194, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NOE, 0 /* can_have_a_subprotocol */, no_master, no_master, "NOE", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CISCOVPN, 0 /* can_have_a_subprotocol */, no_master, no_master, "CiscoVPN", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 10000, 8008, 8009, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 10000, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMSPEAK, 0 /* can_have_a_subprotocol */, no_master, no_master, "TeamSpeak", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKINNY, 0 /* can_have_a_subprotocol */, no_master, no_master, "CiscoSkinny", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 2000, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTCP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTCP", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RSYNC, 0 /* can_have_a_subprotocol */, no_master, no_master, "RSYNC", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 873, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ORACLE, 0 /* can_have_a_subprotocol */, no_master, no_master, "Oracle", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 1521, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CORBA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Corba", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UBUNTUONE, 0 /* can_have_a_subprotocol */, no_master, no_master, "UbuntuONE", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHOIS_DAS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Whois-DAS", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 43, 4343, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_COLLECTD, 0 /* can_have_a_subprotocol */, no_master, no_master, "Collectd", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 25826, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOCKS, 0 /* can_have_a_subprotocol */, no_master, no_master, "SOCKS", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 1080, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 1080, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TFTP, 0 /* can_have_a_subprotocol */, no_master, no_master, "TFTP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 69, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTMP, 0 /* can_have_a_subprotocol */, no_master, no_master, "RTMP", NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 1935, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PANDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Pando_Media_Booster", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEGACO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Megaco", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 2944, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_REDIS, 0 /* can_have_a_subprotocol */, no_master, no_master, "Redis", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 6379, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZMQ, 0 /* can_have_a_subprotocol */, no_master, no_master, "ZeroMQ", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_VHUA, 0 /* can_have_a_subprotocol */, no_master, no_master, "VHUA", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 58267, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STARCRAFT, 0 /* can_have_a_subprotocol */, no_master, no_master, "Starcraft", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 1119, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 1119, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_UBNTAC2, 0 /* can_have_a_subprotocol */, no_master, no_master, "UBNTAC2", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 10001, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VIBER, 0 /* can_have_a_subprotocol */, no_master, no_master, "Viber", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 7985, 5242, 5243, 4244, 0), /* TCP */ ndpi_build_default_ports(ports_b, 7985, 7987, 5242, 5243, 4244)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_COAP, 0 /* can_have_a_subprotocol */, no_master, no_master, "COAP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 5683, 5684, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MQTT, 0 /* can_have_a_subprotocol */, no_master, no_master, "MQTT", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 1883, 8883, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOMEIP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SOMEIP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 30491, 30501, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 30491, 30501, 30490, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RX, 0 /* can_have_a_subprotocol */, no_master, no_master, "RX", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_GIT, 0 /* can_have_a_subprotocol */, no_master, no_master, "Git", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 9418, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DRDA, 0 /* can_have_a_subprotocol */, no_master, no_master, "DRDA", NDPI_PROTOCOL_CATEGORY_DATABASE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HANGOUT_DUO, 0 /* can_have_a_subprotocol */, no_master, no_master, "GoogleHangoutDuo", NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BJNP, 0 /* can_have_a_subprotocol */, no_master, no_master, "BJNP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 8612, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMPP, 0 /* can_have_a_subprotocol */, no_master, no_master, "SMPP", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_OOKLA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Ookla", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMQP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AMQP", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_DNSCRYPT, 0 /* can_have_a_subprotocol */, no_master, no_master, "DNScrypt", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */ ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */ ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TINC, 0 /* can_have_a_subprotocol */, no_master, no_master, "TINC", NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 655, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 655, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FIX, 0 /* can_have_a_subprotocol */, no_master, no_master, "FIX", NDPI_PROTOCOL_CATEGORY_RPC, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_NINTENDO, 0 /* can_have_a_subprotocol */, no_master, no_master, "Nintendo", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CSGO, 0 /* can_have_a_subprotocol */, no_master, no_master, "CSGO", NDPI_PROTOCOL_CATEGORY_GAME, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AJP, 0 /* can_have_a_subprotocol */, no_master, no_master, "AJP", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 8009, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TARGUS_GETDATA, 0 /* can_have_a_subprotocol */, no_master, no_master, "Targus Dataspeed", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5001, 5201, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5001, 5201, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMAZON_VIDEO, 0 /* can_have_a_subprotocol */, no_master, no_master, "AmazonVideo", NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNP3, 1 /* no subprotocol */, no_master, no_master, "DNP3", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 20000, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IEC60870, 1 /* no subprotocol */, no_master, no_master, "IEC60870", NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */ ndpi_build_default_ports(ports_a, 2404, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BLOOMBERG, 1 /* no subprotocol */, no_master, no_master, "Bloomberg", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CAPWAP, 1 /* no subprotocol */, no_master, no_master, "CAPWAP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 5246, 5247, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZABBIX, 1 /* no subprotocol */, no_master, no_master, "Zabbix", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 10050, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_S7COMM, 1 /* no subprotocol */, no_master, no_master, "s7comm", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 102, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MSTEAMS, 1 /* no subprotocol */, no_master, no_master, "Teams", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */ ); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBSOCKET, 1 /* can_have_a_subprotocol */, no_master, no_master, "WebSocket", NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ANYDESK, 1 /* no subprotocol */, no_master, no_master, "AnyDesk", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_main.c" #endif /* calling function for host and content matched protocols */ init_string_based_protocols(ndpi_str); ndpi_validate_protocol_initialization(ndpi_str); } /* ****************************************************** */ #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_protocols.c" #endif /* ****************************************************** */ static int ac_match_handler(AC_MATCH_t *m, AC_TEXT_t *txt, AC_REP_t *match) { int min_len = (txt->length < m->patterns->length) ? txt->length : m->patterns->length; char buf[64] = {'\0'}, *whatfound; int min_buf_len = (txt->length > 63 /* sizeof(buf)-1 */) ? 63 : txt->length; u_int buf_len = strlen(buf); strncpy(buf, txt->astring, min_buf_len); buf[min_buf_len] = '\0'; #ifdef MATCH_DEBUG printf("Searching [to search: %s/%u][pattern: %s/%u] [len: %d][match_num: %u][%s]\n", buf, (unigned int) txt->length, m->patterns->astring, (unigned int) m->patterns->length, min_len, m->match_num, m->patterns->astring); #endif whatfound = strstr(buf, m->patterns->astring); #ifdef MATCH_DEBUG printf("[NDPI] %s() [searching=%s][pattern=%s][%s][%c]\n", __FUNCTION__, buf, m->patterns->astring, whatfound ? whatfound : "<NULL>", whatfound[-1]); #endif if(whatfound) { /* The patch below allows in case of pattern ws.amazon.com to avoid matching aws.amazon.com whereas a.ws.amazon.com has to match */ if((whatfound != buf) && (m->patterns->astring[0] != '.') /* The searched pattern does not start with . */ && strchr(m->patterns->astring, '.') /* The matched pattern has a . (e.g. numeric or sym IPs) */) { int len = strlen(m->patterns->astring); if((whatfound[-1] != '.') || ((m->patterns->astring[len - 1] != '.') && (whatfound[len] != '\0') /* endsWith does not hold here */)) { return(0); } else { memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t)); /* Partial match? */ return(0); /* Keep searching as probably there is a better match */ } } } /* Return 1 for stopping to the first match. We might consider searching for the more specific match, paying more cpu cycles. */ memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t)); if(((buf_len >= min_len) && (strncmp(&buf[buf_len - min_len], m->patterns->astring, min_len) == 0)) || (strncmp(buf, m->patterns->astring, min_len) == 0) /* begins with */ ) { #ifdef MATCH_DEBUG printf("Found match [%s][%s] [len: %d]" // "[proto_id: %u]" "\n", buf, m->patterns->astring, min_len /* , *matching_protocol_id */); #endif return(1); /* If the pattern found matches the string at the beginning we stop here */ } else { #ifdef MATCH_DEBUG printf("NO match found: continue\n"); #endif return(0); /* 0 to continue searching, !0 to stop */ } } /* ******************************************************************** */ static int fill_prefix_v4(prefix_t *p, const struct in_addr *a, int b, int mb) { if(b < 0 || b > mb) return(-1); memset(p, 0, sizeof(prefix_t)); memcpy(&p->add.sin, a, (mb + 7) / 8); p->family = AF_INET; p->bitlen = b; p->ref_count = 0; return(0); } /* ******************************************* */ static int fill_prefix_v6(prefix_t *prefix, const struct in6_addr *addr, int bits, int maxbits) { #ifdef PATRICIA_IPV6 if(bits < 0 || bits > maxbits) return -1; memcpy(&prefix->add.sin6, addr, (maxbits + 7) / 8); prefix->family = AF_INET6, prefix->bitlen = bits, prefix->ref_count = 0; return 0; #else return(-1); #endif } /* ******************************************* */ u_int16_t ndpi_network_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin /* network byte order */) { prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix); return(node ? node->value.uv.user_value : NDPI_PROTOCOL_UNKNOWN); } /* ******************************************* */ u_int16_t ndpi_network_port_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin /* network byte order */, u_int16_t port /* network byte order */) { prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix); if(node) { if((node->value.uv.additional_user_value == 0) || (node->value.uv.additional_user_value == port)) return(node->value.uv.user_value); } return(NDPI_PROTOCOL_UNKNOWN); } /* ******************************************* */ #if 0 static u_int8_t tor_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin) { return((ndpi_network_ptree_match(ndpi_str, pin) == NDPI_PROTOCOL_TOR) ? 1 : 0); } #endif /* ******************************************* */ u_int8_t ndpi_is_tor_flow(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; if(packet->tcp != NULL) { if(packet->iph) { if(flow->guessed_host_protocol_id == NDPI_PROTOCOL_TOR) return(1); } } return(0); } /* ******************************************* */ static patricia_node_t *add_to_ptree(patricia_tree_t *tree, int family, void *addr, int bits) { prefix_t prefix; patricia_node_t *node; fill_prefix_v4(&prefix, (struct in_addr *) addr, bits, tree->maxbits); node = ndpi_patricia_lookup(tree, &prefix); if(node) memset(&node->value, 0, sizeof(node->value)); return(node); } /* ******************************************* */ /* Load a file containing IPv4 addresses in CIDR format as 'protocol_id' Return: the number of entries loaded or -1 in case of error */ int ndpi_load_ipv4_ptree(struct ndpi_detection_module_struct *ndpi_str, const char *path, u_int16_t protocol_id) { char buffer[128], *line, *addr, *cidr, *saveptr; FILE *fd; int len; u_int num_loaded = 0; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); return(-1); } while (1) { line = fgets(buffer, sizeof(buffer), fd); if(line == NULL) break; len = strlen(line); if((len <= 1) || (line[0] == '#')) continue; line[len - 1] = '\0'; addr = strtok_r(line, "/", &saveptr); if(addr) { struct in_addr pin; patricia_node_t *node; cidr = strtok_r(NULL, "\n", &saveptr); pin.s_addr = inet_addr(addr); if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, cidr ? atoi(cidr) : 32 /* bits */)) != NULL) { node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = 0 /* port */; num_loaded++; } } } fclose(fd); return(num_loaded); } /* ******************************************* */ static void ndpi_init_ptree_ipv4(struct ndpi_detection_module_struct *ndpi_str, void *ptree, ndpi_network host_list[], u_int8_t skip_tor_hosts) { int i; for (i = 0; host_list[i].network != 0x0; i++) { struct in_addr pin; patricia_node_t *node; if(skip_tor_hosts && (host_list[i].value == NDPI_PROTOCOL_TOR)) continue; pin.s_addr = htonl(host_list[i].network); if((node = add_to_ptree(ptree, AF_INET, &pin, host_list[i].cidr /* bits */)) != NULL) { node->value.uv.user_value = host_list[i].value, node->value.uv.additional_user_value = 0; } } } /* ******************************************* */ static int ndpi_add_host_ip_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, u_int16_t protocol_id) { patricia_node_t *node; struct in_addr pin; int bits = 32; char *ptr = strrchr(value, '/'); u_int16_t port = 0; /* Format ip:8.248.73.247:443 */ char *double_column; if(ptr) { ptr[0] = '\0'; ptr++; if((double_column = strrchr(ptr, ':')) != NULL) { double_column[0] = '\0'; port = atoi(&double_column[1]); } if(atoi(ptr) >= 0 && atoi(ptr) <= 32) bits = atoi(ptr); } else { /* Let's check if there is the port defined Example: ip:8.248.73.247:443@AmazonPrime */ double_column = strrchr(value, ':'); if(double_column) { double_column[0] = '\0'; port = atoi(&double_column[1]); } } inet_pton(AF_INET, value, &pin); if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, bits)) != NULL) { node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = htons(port); } return(0); } void set_ndpi_malloc(void *(*__ndpi_malloc)(size_t size)) { _ndpi_malloc = __ndpi_malloc; } void set_ndpi_flow_malloc(void *(*__ndpi_flow_malloc)(size_t size)) { _ndpi_flow_malloc = __ndpi_flow_malloc; } void set_ndpi_free(void (*__ndpi_free)(void *ptr)) { _ndpi_free = __ndpi_free; } void set_ndpi_flow_free(void (*__ndpi_flow_free)(void *ptr)) { _ndpi_flow_free = __ndpi_flow_free; } void ndpi_debug_printf(unsigned int proto, struct ndpi_detection_module_struct *ndpi_str, ndpi_log_level_t log_level, const char *file_name, const char *func_name, int line_number, const char *format, ...) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES va_list args; #define MAX_STR_LEN 250 char str[MAX_STR_LEN]; if(ndpi_str != NULL && log_level > NDPI_LOG_ERROR && proto > 0 && proto < NDPI_MAX_SUPPORTED_PROTOCOLS && !NDPI_ISSET(&ndpi_str->debug_bitmask, proto)) return; va_start(args, format); vsnprintf(str, sizeof(str) - 1, format, args); va_end(args); if(ndpi_str != NULL) { printf("%s:%s:%-3d - [%s]: %s", file_name, func_name, line_number, ndpi_get_proto_name(ndpi_str, proto), str); } else { printf("Proto: %u, %s", proto, str); } #endif } void set_ndpi_debug_function(struct ndpi_detection_module_struct *ndpi_str, ndpi_debug_function_ptr ndpi_debug_printf) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES ndpi_str->ndpi_debug_printf = ndpi_debug_printf; #endif } /* ****************************************** */ /* Keep it in order and in sync with ndpi_protocol_category_t in ndpi_typedefs.h */ static const char *categories[] = { "Unspecified", "Media", "VPN", "Email", "DataTransfer", "Web", "SocialNetwork", "Download-FileTransfer-FileSharing", "Game", "Chat", "VoIP", "Database", "RemoteAccess", "Cloud", "Network", "Collaborative", "RPC", "Streaming", "System", "SoftwareUpdate", "", "", "", "", "", "Music", "Video", "Shopping", "Productivity", "FileSharing", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "Mining", /* 99 */ "Malware", "Advertisement", "Banned_Site", "Site_Unavailable", "Allowed_Site", "Antimalware", }; /* ******************************************************************** */ struct ndpi_detection_module_struct *ndpi_init_detection_module(ndpi_init_prefs prefs) { struct ndpi_detection_module_struct *ndpi_str = ndpi_malloc(sizeof(struct ndpi_detection_module_struct)); int i; if(ndpi_str == NULL) { #ifdef NDPI_ENABLE_DEBUG_MESSAGES NDPI_LOG_ERR(ndpi_str, "ndpi_init_detection_module initial malloc failed for ndpi_str\n"); #endif /* NDPI_ENABLE_DEBUG_MESSAGES */ return(NULL); } memset(ndpi_str, 0, sizeof(struct ndpi_detection_module_struct)); #ifdef NDPI_ENABLE_DEBUG_MESSAGES set_ndpi_debug_function(ndpi_str, (ndpi_debug_function_ptr) ndpi_debug_printf); #endif /* NDPI_ENABLE_DEBUG_MESSAGES */ if((ndpi_str->protocols_ptree = ndpi_New_Patricia(32 /* IPv4 */)) != NULL) ndpi_init_ptree_ipv4(ndpi_str, ndpi_str->protocols_ptree, host_protocol_list, prefs & ndpi_dont_load_tor_hosts); NDPI_BITMASK_RESET(ndpi_str->detection_bitmask); #ifdef NDPI_ENABLE_DEBUG_MESSAGES ndpi_str->user_data = NULL; #endif ndpi_str->ticks_per_second = 1000; /* ndpi_str->ticks_per_second */ ndpi_str->tcp_max_retransmission_window_size = NDPI_DEFAULT_MAX_TCP_RETRANSMISSION_WINDOW_SIZE; ndpi_str->directconnect_connection_ip_tick_timeout = NDPI_DIRECTCONNECT_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->rtsp_connection_timeout = NDPI_RTSP_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->irc_timeout = NDPI_IRC_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->gnutella_timeout = NDPI_GNUTELLA_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->thunder_timeout = NDPI_THUNDER_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->zattoo_connection_timeout = NDPI_ZATTOO_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->jabber_stun_timeout = NDPI_JABBER_STUN_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->jabber_file_transfer_timeout = NDPI_JABBER_FT_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->soulseek_connection_ip_tick_timeout = NDPI_SOULSEEK_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second; ndpi_str->ndpi_num_supported_protocols = NDPI_MAX_SUPPORTED_PROTOCOLS; ndpi_str->ndpi_num_custom_protocols = 0; ndpi_str->host_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->content_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->bigrams_automa.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->impossible_bigrams_automa.ac_automa = ac_automata_init(ac_match_handler); if((sizeof(categories) / sizeof(char *)) != NDPI_PROTOCOL_NUM_CATEGORIES) { NDPI_LOG_ERR(ndpi_str, "[NDPI] invalid categories length: expected %u, got %u\n", NDPI_PROTOCOL_NUM_CATEGORIES, (unsigned int) (sizeof(categories) / sizeof(char *))); return(NULL); } ndpi_str->custom_categories.hostnames.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler); ndpi_str->custom_categories.ipAddresses = ndpi_New_Patricia(32 /* IPv4 */); ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */); if((ndpi_str->custom_categories.ipAddresses == NULL) || (ndpi_str->custom_categories.ipAddresses_shadow == NULL)) return(NULL); ndpi_init_protocol_defaults(ndpi_str); for (i = 0; i < NUM_CUSTOM_CATEGORIES; i++) snprintf(ndpi_str->custom_category_labels[i], CUSTOM_CATEGORY_LABEL_LEN, "User custom category %u", (unsigned int) (i + 1)); return(ndpi_str); } /* *********************************************** */ void ndpi_finalize_initalization(struct ndpi_detection_module_struct *ndpi_str) { u_int i; for (i = 0; i < 4; i++) { ndpi_automa *automa; switch (i) { case 0: automa = &ndpi_str->host_automa; break; case 1: automa = &ndpi_str->content_automa; break; case 2: automa = &ndpi_str->bigrams_automa; break; case 3: automa = &ndpi_str->impossible_bigrams_automa; break; default: automa = NULL; break; } if(automa) { ac_automata_finalize((AC_AUTOMATA_t *) automa->ac_automa); automa->ac_automa_finalized = 1; } } } /* *********************************************** */ /* Wrappers */ void *ndpi_init_automa(void) { return(ac_automata_init(ac_match_handler)); } /* ****************************************************** */ int ndpi_add_string_value_to_automa(void *_automa, char *str, u_int32_t num) { AC_PATTERN_t ac_pattern; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_ERROR_t rc; if(automa == NULL) return(-1); memset(&ac_pattern, 0, sizeof(ac_pattern)); ac_pattern.astring = str; ac_pattern.rep.number = num; ac_pattern.length = strlen(ac_pattern.astring); rc = ac_automata_add(automa, &ac_pattern); return(rc == ACERR_SUCCESS || rc == ACERR_DUPLICATE_PATTERN ? 0 : -1); } /* ****************************************************** */ int ndpi_add_string_to_automa(void *_automa, char *str) { return(ndpi_add_string_value_to_automa(_automa, str, 1)); } /* ****************************************************** */ void ndpi_free_automa(void *_automa) { ac_automata_release((AC_AUTOMATA_t *) _automa, 0); } /* ****************************************************** */ void ndpi_finalize_automa(void *_automa) { ac_automata_finalize((AC_AUTOMATA_t *) _automa); } /* ****************************************************** */ int ndpi_match_string(void *_automa, char *string_to_match) { AC_REP_t match = { NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; int rc; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = strlen(string_to_match); rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; return(rc ? match.number : 0); } /* ****************************************************** */ int ndpi_match_string_protocol_id(void *_automa, char *string_to_match, u_int match_len, u_int16_t *protocol_id, ndpi_protocol_category_t *category, ndpi_protocol_breed_t *breed) { AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; int rc; *protocol_id = (u_int16_t)-1; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = match_len; rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; if(rc) *protocol_id = (u_int16_t)match.number, *category = match.category, *breed = match.breed; else *protocol_id = NDPI_PROTOCOL_UNKNOWN; return((*protocol_id != NDPI_PROTOCOL_UNKNOWN) ? 0 : -1); } /* ****************************************************** */ int ndpi_match_string_value(void *_automa, char *string_to_match, u_int match_len, u_int32_t *num) { AC_TEXT_t ac_input_text; AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa; AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED }; int rc; *num = (u_int32_t)-1; if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0')) return(-2); ac_input_text.astring = string_to_match, ac_input_text.length = match_len; rc = ac_automata_search(automa, &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; if(rc) *num = match.number; else *num = 0; return(rc ? 0 : -1); } /* *********************************************** */ int ndpi_match_custom_category(struct ndpi_detection_module_struct *ndpi_str, char *name, u_int name_len, ndpi_protocol_category_t *category) { ndpi_protocol_breed_t breed; u_int16_t id; int rc = ndpi_match_string_protocol_id(ndpi_str->custom_categories.hostnames.ac_automa, name, name_len, &id, category, &breed); return(rc); } /* *********************************************** */ int ndpi_get_custom_category_match(struct ndpi_detection_module_struct *ndpi_str, char *name_or_ip, u_int name_len, ndpi_protocol_category_t *id) { char ipbuf[64], *ptr; struct in_addr pin; u_int cp_len = ndpi_min(sizeof(ipbuf) - 1, name_len); if(!ndpi_str->custom_categories.categories_loaded) return(-1); if(cp_len > 0) { memcpy(ipbuf, name_or_ip, cp_len); ipbuf[cp_len] = '\0'; } else ipbuf[0] = '\0'; ptr = strrchr(ipbuf, '/'); if(ptr) ptr[0] = '\0'; if(inet_pton(AF_INET, ipbuf, &pin) == 1) { /* Search IP */ prefix_t prefix; patricia_node_t *node; /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, &pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); if(node) { *id = node->value.uv.user_value; return(0); } return(-1); } else { /* Search Host */ return(ndpi_match_custom_category(ndpi_str, name_or_ip, name_len, id)); } } /* *********************************************** */ static void free_ptree_data(void *data) { ; } /* ****************************************************** */ void ndpi_exit_detection_module(struct ndpi_detection_module_struct *ndpi_str) { if(ndpi_str != NULL) { int i; for (i = 0; i < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS); i++) { if(ndpi_str->proto_defaults[i].protoName) ndpi_free(ndpi_str->proto_defaults[i].protoName); } /* NDPI_PROTOCOL_TINC */ if(ndpi_str->tinc_cache) cache_free((cache_t)(ndpi_str->tinc_cache)); if(ndpi_str->ookla_cache) ndpi_lru_free_cache(ndpi_str->ookla_cache); if(ndpi_str->stun_cache) ndpi_lru_free_cache(ndpi_str->stun_cache); if(ndpi_str->msteams_cache) ndpi_lru_free_cache(ndpi_str->msteams_cache); if(ndpi_str->protocols_ptree) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->protocols_ptree, free_ptree_data); if(ndpi_str->udpRoot != NULL) ndpi_tdestroy(ndpi_str->udpRoot, ndpi_free); if(ndpi_str->tcpRoot != NULL) ndpi_tdestroy(ndpi_str->tcpRoot, ndpi_free); if(ndpi_str->host_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->host_automa.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->content_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->content_automa.ac_automa, 0); if(ndpi_str->bigrams_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->bigrams_automa.ac_automa, 0); if(ndpi_str->impossible_bigrams_automa.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->impossible_bigrams_automa.ac_automa, 0); if(ndpi_str->custom_categories.hostnames.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->custom_categories.hostnames_shadow.ac_automa != NULL) ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa, 1 /* free patterns strings memory */); if(ndpi_str->custom_categories.ipAddresses != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data); if(ndpi_str->custom_categories.ipAddresses_shadow != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses_shadow, free_ptree_data); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/ndpi_exit_detection_module.c" #endif ndpi_free(ndpi_str); } } /* ****************************************************** */ int ndpi_get_protocol_id_master_proto(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protocol_id, u_int16_t **tcp_master_proto, u_int16_t **udp_master_proto) { if(protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) { *tcp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_tcp_protoId, *udp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_udp_protoId; return(-1); } *tcp_master_proto = ndpi_str->proto_defaults[protocol_id].master_tcp_protoId, *udp_master_proto = ndpi_str->proto_defaults[protocol_id].master_udp_protoId; return(0); } /* ****************************************************** */ static ndpi_default_ports_tree_node_t *ndpi_get_guessed_protocol_id(struct ndpi_detection_module_struct *ndpi_str, u_int8_t proto, u_int16_t sport, u_int16_t dport) { ndpi_default_ports_tree_node_t node; if(sport && dport) { int low = ndpi_min(sport, dport); int high = ndpi_max(sport, dport); const void *ret; node.default_port = low; /* Check server port first */ ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot, ndpi_default_ports_tree_node_t_cmp); if(ret == NULL) { node.default_port = high; ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot, ndpi_default_ports_tree_node_t_cmp); } if(ret) return(*(ndpi_default_ports_tree_node_t **) ret); } return(NULL); } /* ****************************************************** */ /* These are UDP protocols that must fit a single packet and thus that if have NOT been detected they cannot be guessed as they have been excluded */ u_int8_t is_udp_guessable_protocol(u_int16_t l7_guessed_proto) { switch (l7_guessed_proto) { case NDPI_PROTOCOL_QUIC: case NDPI_PROTOCOL_SNMP: case NDPI_PROTOCOL_NETFLOW: /* TODO: add more protocols (if any missing) */ return(1); } return(0); } /* ****************************************************** */ u_int16_t ndpi_guess_protocol_id(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t proto, u_int16_t sport, u_int16_t dport, u_int8_t *user_defined_proto) { *user_defined_proto = 0; /* Default */ if(sport && dport) { ndpi_default_ports_tree_node_t *found = ndpi_get_guessed_protocol_id(ndpi_str, proto, sport, dport); if(found != NULL) { u_int16_t guessed_proto = found->proto->protoId; /* We need to check if the guessed protocol isn't excluded by nDPI */ if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, guessed_proto) && is_udp_guessable_protocol(guessed_proto)) return(NDPI_PROTOCOL_UNKNOWN); else { *user_defined_proto = found->customUserProto; return(guessed_proto); } } } else { /* No TCP/UDP */ switch (proto) { case NDPI_IPSEC_PROTOCOL_ESP: case NDPI_IPSEC_PROTOCOL_AH: return(NDPI_PROTOCOL_IP_IPSEC); break; case NDPI_GRE_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_GRE); break; case NDPI_ICMP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_ICMP); break; case NDPI_IGMP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_IGMP); break; case NDPI_EGP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_EGP); break; case NDPI_SCTP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_SCTP); break; case NDPI_OSPF_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_OSPF); break; case NDPI_IPIP_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_IP_IN_IP); break; case NDPI_ICMPV6_PROTOCOL_TYPE: return(NDPI_PROTOCOL_IP_ICMPV6); break; case 112: return(NDPI_PROTOCOL_IP_VRRP); break; } } return(NDPI_PROTOCOL_UNKNOWN); } /* ******************************************************************** */ u_int ndpi_get_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_supported_protocols); } /* ******************************************************************** */ #ifdef WIN32 char *strsep(char **sp, char *sep) { char *p, *s; if(sp == NULL || *sp == NULL || **sp == '\0') return(NULL); s = *sp; p = s + strcspn(s, sep); if(*p != '\0') *p++ = '\0'; *sp = p; return(s); } #endif /* ******************************************************************** */ int ndpi_handle_rule(struct ndpi_detection_module_struct *ndpi_str, char *rule, u_int8_t do_add) { char *at, *proto, *elem; ndpi_proto_defaults_t *def; u_int16_t subprotocol_id, i; at = strrchr(rule, '@'); if(at == NULL) { NDPI_LOG_ERR(ndpi_str, "Invalid rule '%s'\n", rule); return(-1); } else at[0] = 0, proto = &at[1]; for (i = 0; proto[i] != '\0'; i++) { switch (proto[i]) { case '/': case '&': case '^': case ':': case ';': case '\'': case '"': case ' ': proto[i] = '_'; break; } } for (i = 0, def = NULL; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) { if(ndpi_str->proto_defaults[i].protoName && strcasecmp(ndpi_str->proto_defaults[i].protoName, proto) == 0) { def = &ndpi_str->proto_defaults[i]; subprotocol_id = i; break; } } if(def == NULL) { if(!do_add) { /* We need to remove a rule */ NDPI_LOG_ERR(ndpi_str, "Unable to find protocol '%s': skipping rule '%s'\n", proto, rule); return(-3); } else { ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS]; u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}; if(ndpi_str->ndpi_num_custom_protocols >= (NDPI_MAX_NUM_CUSTOM_PROTOCOLS - 1)) { NDPI_LOG_ERR(ndpi_str, "Too many protocols defined (%u): skipping protocol %s\n", ndpi_str->ndpi_num_custom_protocols, proto); return(-2); } ndpi_set_proto_defaults( ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, ndpi_str->ndpi_num_supported_protocols, 0 /* can_have_a_subprotocol */, no_master, no_master, proto, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, /* TODO add protocol category support in rules */ ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */, ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); def = &ndpi_str->proto_defaults[ndpi_str->ndpi_num_supported_protocols]; subprotocol_id = ndpi_str->ndpi_num_supported_protocols; ndpi_str->ndpi_num_supported_protocols++, ndpi_str->ndpi_num_custom_protocols++; } } while ((elem = strsep(&rule, ",")) != NULL) { char *attr = elem, *value = NULL; ndpi_port_range range; int is_tcp = 0, is_udp = 0, is_ip = 0; if(strncmp(attr, "tcp:", 4) == 0) is_tcp = 1, value = &attr[4]; else if(strncmp(attr, "udp:", 4) == 0) is_udp = 1, value = &attr[4]; else if(strncmp(attr, "ip:", 3) == 0) is_ip = 1, value = &attr[3]; else if(strncmp(attr, "host:", 5) == 0) { /* host:"<value>",host:"<value>",.....@<subproto> */ value = &attr[5]; if(value[0] == '"') value++; /* remove leading " */ if(value[strlen(value) - 1] == '"') value[strlen(value) - 1] = '\0'; /* remove trailing " */ } if(is_tcp || is_udp) { u_int p_low, p_high; if(sscanf(value, "%u-%u", &p_low, &p_high) == 2) range.port_low = p_low, range.port_high = p_high; else range.port_low = range.port_high = atoi(&elem[4]); if(do_add) addDefaultPort(ndpi_str, &range, def, 1 /* Custom user proto */, is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot, __FUNCTION__, __LINE__); else removeDefaultPort(&range, def, is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot); } else if(is_ip) { /* NDPI_PROTOCOL_TOR */ ndpi_add_host_ip_subprotocol(ndpi_str, value, subprotocol_id); } else { if(do_add) ndpi_add_host_url_subprotocol(ndpi_str, value, subprotocol_id, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_ACCEPTABLE); else ndpi_remove_host_url_subprotocol(ndpi_str, value, subprotocol_id); } } return(0); } /* ******************************************************************** */ /* * Format: * * <host|ip> <category_id> * * Notes: * - host and category are separated by a single TAB * - empty lines or lines starting with # are ignored */ int ndpi_load_categories_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) { char buffer[512], *line, *name, *category, *saveptr; FILE *fd; int len, num = 0; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); return(-1); } while (1) { line = fgets(buffer, sizeof(buffer), fd); if(line == NULL) break; len = strlen(line); if((len <= 1) || (line[0] == '#')) continue; line[len - 1] = '\0'; name = strtok_r(line, "\t", &saveptr); if(name) { category = strtok_r(NULL, "\t", &saveptr); if(category) { int rc = ndpi_load_category(ndpi_str, name, (ndpi_protocol_category_t) atoi(category)); if(rc >= 0) num++; } } } fclose(fd); ndpi_enable_loaded_categories(ndpi_str); return(num); } /* ******************************************************************** */ /* Format: <tcp|udp>:<port>,<tcp|udp>:<port>,.....@<proto> Subprotocols Format: host:"<value>",host:"<value>",.....@<subproto> IP based Subprotocols Format (<value> is IP or CIDR): ip:<value>,ip:<value>,.....@<subproto> Example: tcp:80,tcp:3128@HTTP udp:139@NETBIOS */ int ndpi_load_protocols_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) { FILE *fd; char *buffer, *old_buffer; int chunk_len = 512, buffer_len = chunk_len, old_buffer_len; int i, rc = -1; fd = fopen(path, "r"); if(fd == NULL) { NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno)); goto error; } buffer = ndpi_malloc(buffer_len); if(buffer == NULL) { NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n"); goto close_fd; } while (1) { char *line = buffer; int line_len = buffer_len; while ((line = fgets(line, line_len, fd)) != NULL && line[strlen(line) - 1] != '\n') { i = strlen(line); old_buffer = buffer; old_buffer_len = buffer_len; buffer_len += chunk_len; buffer = ndpi_realloc(old_buffer, old_buffer_len, buffer_len); if(buffer == NULL) { NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n"); ndpi_free(old_buffer); goto close_fd; } line = &buffer[i]; line_len = chunk_len; } if(!line) /* safety check */ break; i = strlen(buffer); if((i <= 1) || (buffer[0] == '#')) continue; else buffer[i - 1] = '\0'; ndpi_handle_rule(ndpi_str, buffer, 1); } rc = 0; ndpi_free(buffer); close_fd: fclose(fd); error: return(rc); } /* ******************************************************************** */ /* ntop */ void ndpi_set_bitmask_protocol_detection(char *label, struct ndpi_detection_module_struct *ndpi_str, const NDPI_PROTOCOL_BITMASK *detection_bitmask, const u_int32_t idx, u_int16_t ndpi_protocol_id, void (*func)(struct ndpi_detection_module_struct *, struct ndpi_flow_struct *flow), const NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_bitmask, u_int8_t b_save_bitmask_unknow, u_int8_t b_add_detection_bitmask) { /* Compare specify protocol bitmask with main detection bitmask */ if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(*detection_bitmask, ndpi_protocol_id) != 0) { #ifdef DEBUG NDPI_LOG_DBG2(ndpi_str, "[NDPI] ndpi_set_bitmask_protocol_detection: %s : [callback_buffer] idx= %u, [proto_defaults] " "protocol_id=%u\n", label, idx, ndpi_protocol_id); #endif if(ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx != 0) { NDPI_LOG_DBG2(ndpi_str, "[NDPI] Internal error: protocol %s/%u has been already registered\n", label, ndpi_protocol_id); #ifdef DEBUG } else { NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding %s with protocol id %d\n", label, ndpi_protocol_id); #endif } /* Set function and index protocol within proto_default structure for port protocol detection and callback_buffer function for DPI protocol detection */ ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx = idx; ndpi_str->proto_defaults[ndpi_protocol_id].func = ndpi_str->callback_buffer[idx].func = func; /* Set ndpi_selection_bitmask for protocol */ ndpi_str->callback_buffer[idx].ndpi_selection_bitmask = ndpi_selection_bitmask; /* Reset protocol detection bitmask via NDPI_PROTOCOL_UNKNOWN and than add specify protocol bitmast to callback buffer. */ if(b_save_bitmask_unknow) NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, NDPI_PROTOCOL_UNKNOWN); if(b_add_detection_bitmask) NDPI_ADD_PROTOCOL_TO_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, ndpi_protocol_id); NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].excluded_protocol_bitmask, ndpi_protocol_id); } } /* ******************************************************************** */ void ndpi_set_protocol_detection_bitmask2(struct ndpi_detection_module_struct *ndpi_str, const NDPI_PROTOCOL_BITMASK *dbm) { NDPI_PROTOCOL_BITMASK detection_bitmask_local; NDPI_PROTOCOL_BITMASK *detection_bitmask = &detection_bitmask_local; u_int32_t a = 0; NDPI_BITMASK_SET(detection_bitmask_local, *dbm); NDPI_BITMASK_SET(ndpi_str->detection_bitmask, *dbm); /* set this here to zero to be interrupt safe */ ndpi_str->callback_buffer_size = 0; /* HTTP */ init_http_dissector(ndpi_str, &a, detection_bitmask); /* STARCRAFT */ init_starcraft_dissector(ndpi_str, &a, detection_bitmask); /* TLS */ init_tls_dissector(ndpi_str, &a, detection_bitmask); /* STUN */ init_stun_dissector(ndpi_str, &a, detection_bitmask); /* RTP */ init_rtp_dissector(ndpi_str, &a, detection_bitmask); /* RTSP */ init_rtsp_dissector(ndpi_str, &a, detection_bitmask); /* RDP */ init_rdp_dissector(ndpi_str, &a, detection_bitmask); /* SIP */ init_sip_dissector(ndpi_str, &a, detection_bitmask); /* IMO */ init_imo_dissector(ndpi_str, &a, detection_bitmask); /* Teredo */ init_teredo_dissector(ndpi_str, &a, detection_bitmask); /* EDONKEY */ init_edonkey_dissector(ndpi_str, &a, detection_bitmask); /* FASTTRACK */ init_fasttrack_dissector(ndpi_str, &a, detection_bitmask); /* GNUTELLA */ init_gnutella_dissector(ndpi_str, &a, detection_bitmask); /* DIRECTCONNECT */ init_directconnect_dissector(ndpi_str, &a, detection_bitmask); /* NATS */ init_nats_dissector(ndpi_str, &a, detection_bitmask); /* APPLEJUICE */ init_applejuice_dissector(ndpi_str, &a, detection_bitmask); /* SOULSEEK */ init_soulseek_dissector(ndpi_str, &a, detection_bitmask); /* SOCKS */ init_socks_dissector(ndpi_str, &a, detection_bitmask); /* IRC */ init_irc_dissector(ndpi_str, &a, detection_bitmask); /* JABBER */ init_jabber_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_POP */ init_mail_pop_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_IMAP */ init_mail_imap_dissector(ndpi_str, &a, detection_bitmask); /* MAIL_SMTP */ init_mail_smtp_dissector(ndpi_str, &a, detection_bitmask); /* USENET */ init_usenet_dissector(ndpi_str, &a, detection_bitmask); /* DNS */ init_dns_dissector(ndpi_str, &a, detection_bitmask); /* FILETOPIA */ init_fbzero_dissector(ndpi_str, &a, detection_bitmask); /* VMWARE */ init_vmware_dissector(ndpi_str, &a, detection_bitmask); /* NON_TCP_UDP */ init_non_tcp_udp_dissector(ndpi_str, &a, detection_bitmask); /* SOPCAST */ init_sopcast_dissector(ndpi_str, &a, detection_bitmask); /* TVUPLAYER */ init_tvuplayer_dissector(ndpi_str, &a, detection_bitmask); /* PPSTREAM */ init_ppstream_dissector(ndpi_str, &a, detection_bitmask); /* PPLIVE */ init_pplive_dissector(ndpi_str, &a, detection_bitmask); /* IAX */ init_iax_dissector(ndpi_str, &a, detection_bitmask); /* MGPC */ init_mgpc_dissector(ndpi_str, &a, detection_bitmask); /* ZATTOO */ init_zattoo_dissector(ndpi_str, &a, detection_bitmask); /* QQ */ init_qq_dissector(ndpi_str, &a, detection_bitmask); /* SSH */ init_ssh_dissector(ndpi_str, &a, detection_bitmask); /* AYIYA */ init_ayiya_dissector(ndpi_str, &a, detection_bitmask); /* THUNDER */ init_thunder_dissector(ndpi_str, &a, detection_bitmask); /* VNC */ init_vnc_dissector(ndpi_str, &a, detection_bitmask); /* TEAMVIEWER */ init_teamviewer_dissector(ndpi_str, &a, detection_bitmask); /* DHCP */ init_dhcp_dissector(ndpi_str, &a, detection_bitmask); /* STEAM */ init_steam_dissector(ndpi_str, &a, detection_bitmask); /* HALFLIFE2 */ init_halflife2_dissector(ndpi_str, &a, detection_bitmask); /* XBOX */ init_xbox_dissector(ndpi_str, &a, detection_bitmask); /* HTTP_APPLICATION_ACTIVESYNC */ init_http_activesync_dissector(ndpi_str, &a, detection_bitmask); /* SMB */ init_smb_dissector(ndpi_str, &a, detection_bitmask); /* MINING */ init_mining_dissector(ndpi_str, &a, detection_bitmask); /* TELNET */ init_telnet_dissector(ndpi_str, &a, detection_bitmask); /* NTP */ init_ntp_dissector(ndpi_str, &a, detection_bitmask); /* NFS */ init_nfs_dissector(ndpi_str, &a, detection_bitmask); /* SSDP */ init_ssdp_dissector(ndpi_str, &a, detection_bitmask); /* WORLD_OF_WARCRAFT */ init_world_of_warcraft_dissector(ndpi_str, &a, detection_bitmask); /* POSTGRES */ init_postgres_dissector(ndpi_str, &a, detection_bitmask); /* MYSQL */ init_mysql_dissector(ndpi_str, &a, detection_bitmask); /* BGP */ init_bgp_dissector(ndpi_str, &a, detection_bitmask); /* SNMP */ init_snmp_dissector(ndpi_str, &a, detection_bitmask); /* KONTIKI */ init_kontiki_dissector(ndpi_str, &a, detection_bitmask); /* ICECAST */ init_icecast_dissector(ndpi_str, &a, detection_bitmask); /* SHOUTCAST */ init_shoutcast_dissector(ndpi_str, &a, detection_bitmask); /* KERBEROS */ init_kerberos_dissector(ndpi_str, &a, detection_bitmask); /* OPENFT */ init_openft_dissector(ndpi_str, &a, detection_bitmask); /* SYSLOG */ init_syslog_dissector(ndpi_str, &a, detection_bitmask); /* DIRECT_DOWNLOAD_LINK */ init_directdownloadlink_dissector(ndpi_str, &a, detection_bitmask); /* NETBIOS */ init_netbios_dissector(ndpi_str, &a, detection_bitmask); /* MDNS */ init_mdns_dissector(ndpi_str, &a, detection_bitmask); /* IPP */ init_ipp_dissector(ndpi_str, &a, detection_bitmask); /* LDAP */ init_ldap_dissector(ndpi_str, &a, detection_bitmask); /* WARCRAFT3 */ init_warcraft3_dissector(ndpi_str, &a, detection_bitmask); /* XDMCP */ init_xdmcp_dissector(ndpi_str, &a, detection_bitmask); /* TFTP */ init_tftp_dissector(ndpi_str, &a, detection_bitmask); /* MSSQL_TDS */ init_mssql_tds_dissector(ndpi_str, &a, detection_bitmask); /* PPTP */ init_pptp_dissector(ndpi_str, &a, detection_bitmask); /* STEALTHNET */ init_stealthnet_dissector(ndpi_str, &a, detection_bitmask); /* DHCPV6 */ init_dhcpv6_dissector(ndpi_str, &a, detection_bitmask); /* AFP */ init_afp_dissector(ndpi_str, &a, detection_bitmask); /* check_mk */ init_checkmk_dissector(ndpi_str, &a, detection_bitmask); /* AIMINI */ init_aimini_dissector(ndpi_str, &a, detection_bitmask); /* FLORENSIA */ init_florensia_dissector(ndpi_str, &a, detection_bitmask); /* MAPLESTORY */ init_maplestory_dissector(ndpi_str, &a, detection_bitmask); /* DOFUS */ init_dofus_dissector(ndpi_str, &a, detection_bitmask); /* WORLD_OF_KUNG_FU */ init_world_of_kung_fu_dissector(ndpi_str, &a, detection_bitmask); /* FIESTA */ init_fiesta_dissector(ndpi_str, &a, detection_bitmask); /* CROSSIFIRE */ init_crossfire_dissector(ndpi_str, &a, detection_bitmask); /* GUILDWARS */ init_guildwars_dissector(ndpi_str, &a, detection_bitmask); /* ARMAGETRON */ init_armagetron_dissector(ndpi_str, &a, detection_bitmask); /* DROPBOX */ init_dropbox_dissector(ndpi_str, &a, detection_bitmask); /* SPOTIFY */ init_spotify_dissector(ndpi_str, &a, detection_bitmask); /* RADIUS */ init_radius_dissector(ndpi_str, &a, detection_bitmask); /* CITRIX */ init_citrix_dissector(ndpi_str, &a, detection_bitmask); /* LOTUS_NOTES */ init_lotus_notes_dissector(ndpi_str, &a, detection_bitmask); /* GTP */ init_gtp_dissector(ndpi_str, &a, detection_bitmask); /* DCERPC */ init_dcerpc_dissector(ndpi_str, &a, detection_bitmask); /* NETFLOW */ init_netflow_dissector(ndpi_str, &a, detection_bitmask); /* SFLOW */ init_sflow_dissector(ndpi_str, &a, detection_bitmask); /* H323 */ init_h323_dissector(ndpi_str, &a, detection_bitmask); /* OPENVPN */ init_openvpn_dissector(ndpi_str, &a, detection_bitmask); /* NOE */ init_noe_dissector(ndpi_str, &a, detection_bitmask); /* CISCOVPN */ init_ciscovpn_dissector(ndpi_str, &a, detection_bitmask); /* TEAMSPEAK */ init_teamspeak_dissector(ndpi_str, &a, detection_bitmask); /* TOR */ init_tor_dissector(ndpi_str, &a, detection_bitmask); /* SKINNY */ init_skinny_dissector(ndpi_str, &a, detection_bitmask); /* RTCP */ init_rtcp_dissector(ndpi_str, &a, detection_bitmask); /* RSYNC */ init_rsync_dissector(ndpi_str, &a, detection_bitmask); /* WHOIS_DAS */ init_whois_das_dissector(ndpi_str, &a, detection_bitmask); /* ORACLE */ init_oracle_dissector(ndpi_str, &a, detection_bitmask); /* CORBA */ init_corba_dissector(ndpi_str, &a, detection_bitmask); /* RTMP */ init_rtmp_dissector(ndpi_str, &a, detection_bitmask); /* FTP_CONTROL */ init_ftp_control_dissector(ndpi_str, &a, detection_bitmask); /* FTP_DATA */ init_ftp_data_dissector(ndpi_str, &a, detection_bitmask); /* PANDO */ init_pando_dissector(ndpi_str, &a, detection_bitmask); /* MEGACO */ init_megaco_dissector(ndpi_str, &a, detection_bitmask); /* REDIS */ init_redis_dissector(ndpi_str, &a, detection_bitmask); /* UPnP */ init_upnp_dissector(ndpi_str, &a, detection_bitmask); /* VHUA */ init_vhua_dissector(ndpi_str, &a, detection_bitmask); /* ZMQ */ init_zmq_dissector(ndpi_str, &a, detection_bitmask); /* TELEGRAM */ init_telegram_dissector(ndpi_str, &a, detection_bitmask); /* QUIC */ init_quic_dissector(ndpi_str, &a, detection_bitmask); /* DIAMETER */ init_diameter_dissector(ndpi_str, &a, detection_bitmask); /* APPLE_PUSH */ init_apple_push_dissector(ndpi_str, &a, detection_bitmask); /* EAQ */ init_eaq_dissector(ndpi_str, &a, detection_bitmask); /* KAKAOTALK_VOICE */ init_kakaotalk_voice_dissector(ndpi_str, &a, detection_bitmask); /* MPEGTS */ init_mpegts_dissector(ndpi_str, &a, detection_bitmask); /* UBNTAC2 */ init_ubntac2_dissector(ndpi_str, &a, detection_bitmask); /* COAP */ init_coap_dissector(ndpi_str, &a, detection_bitmask); /* MQTT */ init_mqtt_dissector(ndpi_str, &a, detection_bitmask); /* SOME/IP */ init_someip_dissector(ndpi_str, &a, detection_bitmask); /* RX */ init_rx_dissector(ndpi_str, &a, detection_bitmask); /* GIT */ init_git_dissector(ndpi_str, &a, detection_bitmask); /* HANGOUT */ init_hangout_dissector(ndpi_str, &a, detection_bitmask); /* DRDA */ init_drda_dissector(ndpi_str, &a, detection_bitmask); /* BJNP */ init_bjnp_dissector(ndpi_str, &a, detection_bitmask); /* SMPP */ init_smpp_dissector(ndpi_str, &a, detection_bitmask); /* TINC */ init_tinc_dissector(ndpi_str, &a, detection_bitmask); /* FIX */ init_fix_dissector(ndpi_str, &a, detection_bitmask); /* NINTENDO */ init_nintendo_dissector(ndpi_str, &a, detection_bitmask); /* MODBUS */ init_modbus_dissector(ndpi_str, &a, detection_bitmask); /* CAPWAP */ init_capwap_dissector(ndpi_str, &a, detection_bitmask); /* ZABBIX */ init_zabbix_dissector(ndpi_str, &a, detection_bitmask); /*** Put false-positive sensitive protocols at the end ***/ /* VIBER */ init_viber_dissector(ndpi_str, &a, detection_bitmask); /* SKYPE */ init_skype_dissector(ndpi_str, &a, detection_bitmask); /* BITTORRENT */ init_bittorrent_dissector(ndpi_str, &a, detection_bitmask); /* WHATSAPP */ init_whatsapp_dissector(ndpi_str, &a, detection_bitmask); /* OOKLA */ init_ookla_dissector(ndpi_str, &a, detection_bitmask); /* AMQP */ init_amqp_dissector(ndpi_str, &a, detection_bitmask); /* CSGO */ init_csgo_dissector(ndpi_str, &a, detection_bitmask); /* LISP */ init_lisp_dissector(ndpi_str, &a, detection_bitmask); /* AJP */ init_ajp_dissector(ndpi_str, &a, detection_bitmask); /* Memcached */ init_memcached_dissector(ndpi_str, &a, detection_bitmask); /* Nest Log Sink */ init_nest_log_sink_dissector(ndpi_str, &a, detection_bitmask); /* WireGuard VPN */ init_wireguard_dissector(ndpi_str, &a, detection_bitmask); /* Amazon_Video */ init_amazon_video_dissector(ndpi_str, &a, detection_bitmask); /* Targus Getdata */ init_targus_getdata_dissector(ndpi_str, &a, detection_bitmask); /* S7 comm */ init_s7comm_dissector(ndpi_str, &a, detection_bitmask); /* IEC 60870-5-104 */ init_104_dissector(ndpi_str, &a, detection_bitmask); /* WEBSOCKET */ init_websocket_dissector(ndpi_str, &a, detection_bitmask); #ifdef CUSTOM_NDPI_PROTOCOLS #include "../../../nDPI-custom/custom_ndpi_main_init.c" #endif /* ----------------------------------------------------------------- */ ndpi_str->callback_buffer_size = a; NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size is %u\n", ndpi_str->callback_buffer_size); /* now build the specific buffer for tcp, udp and non_tcp_udp */ ndpi_str->callback_buffer_size_tcp_payload = 0; ndpi_str->callback_buffer_size_tcp_no_payload = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_tcp_payload, adding buffer %u as entry %u\n", a, ndpi_str->callback_buffer_size_tcp_payload); memcpy(&ndpi_str->callback_buffer_tcp_payload[ndpi_str->callback_buffer_size_tcp_payload], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_tcp_payload++; if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) == 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2( ndpi_str, "\tcallback_buffer_tcp_no_payload, additional adding buffer %u to no_payload process\n", a); memcpy(&ndpi_str->callback_buffer_tcp_no_payload[ndpi_str->callback_buffer_size_tcp_no_payload], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_tcp_no_payload++; } } } ndpi_str->callback_buffer_size_udp = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size_udp: adding buffer : %u as entry %u\n", a, ndpi_str->callback_buffer_size_udp); memcpy(&ndpi_str->callback_buffer_udp[ndpi_str->callback_buffer_size_udp], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_udp++; } } ndpi_str->callback_buffer_size_non_tcp_udp = 0; for (a = 0; a < ndpi_str->callback_buffer_size; a++) { if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP)) == 0 || (ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC) != 0) { if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "callback_buffer_non_tcp_udp: adding buffer : %u as entry %u\n", a, ndpi_str->callback_buffer_size_non_tcp_udp); memcpy(&ndpi_str->callback_buffer_non_tcp_udp[ndpi_str->callback_buffer_size_non_tcp_udp], &ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct)); ndpi_str->callback_buffer_size_non_tcp_udp++; } } } #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* handle extension headers in IPv6 packets * arguments: * l4ptr: pointer to the byte following the initial IPv6 header * l4len: the length of the IPv6 packet excluding the IPv6 header * nxt_hdr: next header value from the IPv6 header * result: * l4ptr: pointer to the start of the actual packet payload * l4len: length of the actual payload * nxt_hdr: protocol of the actual payload * returns 0 upon success and 1 upon failure */ int ndpi_handle_ipv6_extension_headers(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t **l4ptr, u_int16_t *l4len, u_int8_t *nxt_hdr) { while ((*nxt_hdr == 0 || *nxt_hdr == 43 || *nxt_hdr == 44 || *nxt_hdr == 60 || *nxt_hdr == 135 || *nxt_hdr == 59)) { u_int16_t ehdr_len; // no next header if(*nxt_hdr == 59) { return(1); } // fragment extension header has fixed size of 8 bytes and the first byte is the next header type if(*nxt_hdr == 44) { if(*l4len < 8) { return(1); } *nxt_hdr = (*l4ptr)[0]; *l4len -= 8; (*l4ptr) += 8; continue; } // the other extension headers have one byte for the next header type // and one byte for the extension header length in 8 byte steps minus the first 8 bytes if(*l4len < 2) { return(1); } ehdr_len = (*l4ptr)[1]; ehdr_len *= 8; ehdr_len += 8; if(*l4len < ehdr_len) { return(1); } *nxt_hdr = (*l4ptr)[0]; *l4len -= ehdr_len; (*l4ptr) += ehdr_len; } return(0); } #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ static u_int8_t ndpi_iph_is_valid_and_not_fragmented(const struct ndpi_iphdr *iph, const u_int16_t ipsize) { //#ifdef REQUIRE_FULL_PACKETS if(ipsize < iph->ihl * 4 || ipsize < ntohs(iph->tot_len) || ntohs(iph->tot_len) < iph->ihl * 4 || (iph->frag_off & htons(0x1FFF)) != 0) { return(0); } //#endif return(1); } static u_int8_t ndpi_detection_get_l4_internal(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t *l3, u_int16_t l3_len, const u_int8_t **l4_return, u_int16_t *l4_len_return, u_int8_t *l4_protocol_return, u_int32_t flags) { const struct ndpi_iphdr *iph = NULL; #ifdef NDPI_DETECTION_SUPPORT_IPV6 const struct ndpi_ipv6hdr *iph_v6 = NULL; #endif u_int16_t l4len = 0; const u_int8_t *l4ptr = NULL; u_int8_t l4protocol = 0; if(l3 == NULL || l3_len < sizeof(struct ndpi_iphdr)) return(1); if((iph = (const struct ndpi_iphdr *) l3) == NULL) return(1); if(iph->version == IPVERSION && iph->ihl >= 5) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n"); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(iph->version == 6 && l3_len >= sizeof(struct ndpi_ipv6hdr)) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n"); iph_v6 = (const struct ndpi_ipv6hdr *) l3; iph = NULL; } #endif else { return(1); } if((flags & NDPI_DETECTION_ONLY_IPV6) && iph != NULL) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header found but excluded by flag\n"); return(1); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if((flags & NDPI_DETECTION_ONLY_IPV4) && iph_v6 != NULL) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header found but excluded by flag\n"); return(1); } #endif if(iph != NULL && ndpi_iph_is_valid_and_not_fragmented(iph, l3_len)) { u_int16_t len = ntohs(iph->tot_len); u_int16_t hlen = (iph->ihl * 4); l4ptr = (((const u_int8_t *) iph) + iph->ihl * 4); if(len == 0) len = l3_len; l4len = (len > hlen) ? (len - hlen) : 0; l4protocol = iph->protocol; } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(iph_v6 != NULL && (l3_len - sizeof(struct ndpi_ipv6hdr)) >= ntohs(iph_v6->ip6_hdr.ip6_un1_plen)) { l4ptr = (((const u_int8_t *) iph_v6) + sizeof(struct ndpi_ipv6hdr)); l4len = ntohs(iph_v6->ip6_hdr.ip6_un1_plen); l4protocol = iph_v6->ip6_hdr.ip6_un1_nxt; // we need to handle IPv6 extension headers if present if(ndpi_handle_ipv6_extension_headers(ndpi_str, &l4ptr, &l4len, &l4protocol) != 0) { return(1); } } #endif else { return(1); } if(l4_return != NULL) { *l4_return = l4ptr; } if(l4_len_return != NULL) { *l4_len_return = l4len; } if(l4_protocol_return != NULL) { *l4_protocol_return = l4protocol; } return(0); } /* ************************************************ */ void ndpi_apply_flow_protocol_to_packet(struct ndpi_flow_struct *flow, struct ndpi_packet_struct *packet) { memcpy(&packet->detected_protocol_stack, &flow->detected_protocol_stack, sizeof(packet->detected_protocol_stack)); memcpy(&packet->protocol_stack_info, &flow->protocol_stack_info, sizeof(packet->protocol_stack_info)); } /* ************************************************ */ static int ndpi_init_packet_header(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, unsigned short packetlen) { const struct ndpi_iphdr *decaps_iph = NULL; u_int16_t l3len; u_int16_t l4len; const u_int8_t *l4ptr; u_int8_t l4protocol; u_int8_t l4_result; if(!flow) return(1); /* reset payload_packet_len, will be set if ipv4 tcp or udp */ flow->packet.payload_packet_len = 0; flow->packet.l4_packet_len = 0; flow->packet.l3_packet_len = packetlen; flow->packet.tcp = NULL, flow->packet.udp = NULL; flow->packet.generic_l4_ptr = NULL; #ifdef NDPI_DETECTION_SUPPORT_IPV6 flow->packet.iphv6 = NULL; #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ ndpi_apply_flow_protocol_to_packet(flow, &flow->packet); l3len = flow->packet.l3_packet_len; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iph != NULL) { #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ decaps_iph = flow->packet.iph; #ifdef NDPI_DETECTION_SUPPORT_IPV6 } #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ if(decaps_iph && decaps_iph->version == IPVERSION && decaps_iph->ihl >= 5) { NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n"); } #ifdef NDPI_DETECTION_SUPPORT_IPV6 else if(decaps_iph && decaps_iph->version == 6 && l3len >= sizeof(struct ndpi_ipv6hdr) && (ndpi_str->ip_version_limit & NDPI_DETECTION_ONLY_IPV4) == 0) { NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n"); flow->packet.iphv6 = (struct ndpi_ipv6hdr *) flow->packet.iph; flow->packet.iph = NULL; } #endif else { flow->packet.iph = NULL; return(1); } /* needed: * - unfragmented packets * - ip header <= packet len * - ip total length >= packet len */ l4ptr = NULL; l4len = 0; l4protocol = 0; l4_result = ndpi_detection_get_l4_internal(ndpi_str, (const u_int8_t *) decaps_iph, l3len, &l4ptr, &l4len, &l4protocol, 0); if(l4_result != 0) { return(1); } flow->packet.l4_protocol = l4protocol; flow->packet.l4_packet_len = l4len; flow->l4_proto = l4protocol; /* tcp / udp detection */ if(l4protocol == IPPROTO_TCP && flow->packet.l4_packet_len >= 20 /* min size of tcp */) { /* tcp */ flow->packet.tcp = (struct ndpi_tcphdr *) l4ptr; if(flow->packet.l4_packet_len >= flow->packet.tcp->doff * 4) { flow->packet.payload_packet_len = flow->packet.l4_packet_len - flow->packet.tcp->doff * 4; flow->packet.actual_payload_len = flow->packet.payload_packet_len; flow->packet.payload = ((u_int8_t *) flow->packet.tcp) + (flow->packet.tcp->doff * 4); /* check for new tcp syn packets, here * idea: reset detection state if a connection is unknown */ if(flow->packet.tcp->syn != 0 && flow->packet.tcp->ack == 0 && flow->init_finished != 0 && flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { u_int8_t backup; u_int16_t backup1, backup2; if(flow->http.url) { ndpi_free(flow->http.url); flow->http.url = NULL; } if(flow->http.content_type) { ndpi_free(flow->http.content_type); flow->http.content_type = NULL; } if(flow->http.user_agent) { ndpi_free(flow->http.user_agent); flow->http.user_agent = NULL; } if(flow->kerberos_buf.pktbuf) { ndpi_free(flow->kerberos_buf.pktbuf); flow->kerberos_buf.pktbuf = NULL; } if(flow->l4.tcp.tls.message.buffer) { ndpi_free(flow->l4.tcp.tls.message.buffer); flow->l4.tcp.tls.message.buffer = NULL; flow->l4.tcp.tls.message.buffer_len = flow->l4.tcp.tls.message.buffer_used = 0; } backup = flow->num_processed_pkts; backup1 = flow->guessed_protocol_id; backup2 = flow->guessed_host_protocol_id; memset(flow, 0, sizeof(*(flow))); flow->num_processed_pkts = backup; flow->guessed_protocol_id = backup1; flow->guessed_host_protocol_id = backup2; NDPI_LOG_DBG(ndpi_str, "tcp syn packet for unknown protocol, reset detection state\n"); } } else { /* tcp header not complete */ flow->packet.tcp = NULL; } } else if(l4protocol == IPPROTO_UDP && flow->packet.l4_packet_len >= 8 /* size of udp */) { flow->packet.udp = (struct ndpi_udphdr *) l4ptr; flow->packet.payload_packet_len = flow->packet.l4_packet_len - 8; flow->packet.payload = ((u_int8_t *) flow->packet.udp) + 8; } else { flow->packet.generic_l4_ptr = l4ptr; } return(0); } /* ************************************************ */ void ndpi_connection_tracking(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { if(!flow) { return; } else { /* const for gcc code optimization and cleaner code */ struct ndpi_packet_struct *packet = &flow->packet; const struct ndpi_iphdr *iph = packet->iph; #ifdef NDPI_DETECTION_SUPPORT_IPV6 const struct ndpi_ipv6hdr *iphv6 = packet->iphv6; #endif const struct ndpi_tcphdr *tcph = packet->tcp; const struct ndpi_udphdr *udph = flow->packet.udp; packet->tcp_retransmission = 0, packet->packet_direction = 0; if(ndpi_str->direction_detect_disable) { packet->packet_direction = flow->packet_direction; } else { if(iph != NULL && ntohl(iph->saddr) < ntohl(iph->daddr)) packet->packet_direction = 1; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(iphv6 != NULL && NDPI_COMPARE_IPV6_ADDRESS_STRUCTS(&iphv6->ip6_src, &iphv6->ip6_dst) != 0) packet->packet_direction = 1; #endif } packet->packet_lines_parsed_complete = 0; if(flow->init_finished == 0) { flow->init_finished = 1; flow->setup_packet_direction = packet->packet_direction; } if(tcph != NULL) { /* reset retried bytes here before setting it */ packet->num_retried_bytes = 0; if(!ndpi_str->direction_detect_disable) packet->packet_direction = (ntohs(tcph->source) < ntohs(tcph->dest)) ? 1 : 0; if(tcph->syn != 0 && tcph->ack == 0 && flow->l4.tcp.seen_syn == 0 && flow->l4.tcp.seen_syn_ack == 0 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_syn = 1; } if(tcph->syn != 0 && tcph->ack != 0 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 0 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_syn_ack = 1; } if(tcph->syn == 0 && tcph->ack == 1 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 1 && flow->l4.tcp.seen_ack == 0) { flow->l4.tcp.seen_ack = 1; } if((flow->next_tcp_seq_nr[0] == 0 && flow->next_tcp_seq_nr[1] == 0) || (flow->next_tcp_seq_nr[0] == 0 || flow->next_tcp_seq_nr[1] == 0)) { /* initialize tcp sequence counters */ /* the ack flag needs to be set to get valid sequence numbers from the other * direction. Usually it will catch the second packet syn+ack but it works * also for asymmetric traffic where it will use the first data packet * * if the syn flag is set add one to the sequence number, * otherwise use the payload length. */ if(tcph->ack != 0) { flow->next_tcp_seq_nr[flow->packet.packet_direction] = ntohl(tcph->seq) + (tcph->syn ? 1 : packet->payload_packet_len); flow->next_tcp_seq_nr[1 - flow->packet.packet_direction] = ntohl(tcph->ack_seq); } } else if(packet->payload_packet_len > 0) { /* check tcp sequence counters */ if(((u_int32_t)(ntohl(tcph->seq) - flow->next_tcp_seq_nr[packet->packet_direction])) > ndpi_str->tcp_max_retransmission_window_size) { packet->tcp_retransmission = 1; /* CHECK IF PARTIAL RETRY IS HAPPENING */ if((flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq) < packet->payload_packet_len)) { /* num_retried_bytes actual_payload_len hold info about the partial retry analyzer which require this info can make use of this info Other analyzer can use packet->payload_packet_len */ packet->num_retried_bytes = (u_int16_t)(flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq)); packet->actual_payload_len = packet->payload_packet_len - packet->num_retried_bytes; flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len; } } /* normal path actual_payload_len is initialized to payload_packet_len during tcp header parsing itself. It will be changed only in case of retransmission */ else { packet->num_retried_bytes = 0; flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len; } } if(tcph->rst) { flow->next_tcp_seq_nr[0] = 0; flow->next_tcp_seq_nr[1] = 0; } } else if(udph != NULL) { if(!ndpi_str->direction_detect_disable) packet->packet_direction = (htons(udph->source) < htons(udph->dest)) ? 1 : 0; } if(flow->packet_counter < MAX_PACKET_COUNTER && packet->payload_packet_len) { flow->packet_counter++; } if(flow->packet_direction_counter[packet->packet_direction] < MAX_PACKET_COUNTER && packet->payload_packet_len) { flow->packet_direction_counter[packet->packet_direction]++; } if(flow->byte_counter[packet->packet_direction] + packet->payload_packet_len > flow->byte_counter[packet->packet_direction]) { flow->byte_counter[packet->packet_direction] += packet->payload_packet_len; } } } /* ************************************************ */ void check_ndpi_other_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { if(!flow) return; void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } for (a = 0; a < ndpi_str->callback_buffer_size_non_tcp_udp; a++) { if((func != ndpi_str->callback_buffer_non_tcp_udp[a].func) && (ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_non_tcp_udp[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_non_tcp_udp[a].detection_bitmask, detection_bitmask) != 0) { if(ndpi_str->callback_buffer_non_tcp_udp[a].func != NULL) ndpi_str->callback_buffer_non_tcp_udp[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } /* ************************************************ */ void check_ndpi_udp_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { for (a = 0; a < ndpi_str->callback_buffer_size_udp; a++) { if((func != ndpi_str->callback_buffer_udp[a].func) && (ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_udp[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_udp[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_udp[a].func(ndpi_str, flow); // NDPI_LOG_DBG(ndpi_str, "[UDP,CALL] dissector of protocol as callback_buffer idx = %d\n",a); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } else if(_ndpi_debug_callbacks) NDPI_LOG_DBG2(ndpi_str, "[UDP,SKIP] dissector of protocol as callback_buffer idx = %d\n", a); } } } /* ************************************************ */ void check_ndpi_tcp_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { void *func = NULL; u_int32_t a; u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx; int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId; NDPI_PROTOCOL_BITMASK detection_bitmask; NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]); if(flow->packet.payload_packet_len != 0) { if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { for (a = 0; a < ndpi_str->callback_buffer_size_tcp_payload; a++) { if((func != ndpi_str->callback_buffer_tcp_payload[a].func) && (ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_tcp_payload[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_payload[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_tcp_payload[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } } else { /* no payload */ if((proto_id != NDPI_PROTOCOL_UNKNOWN) && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 && (ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) { if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL) && ((ndpi_str->callback_buffer[flow->guessed_protocol_id].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) == 0)) ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow), func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func; } for (a = 0; a < ndpi_str->callback_buffer_size_tcp_no_payload; a++) { if((func != ndpi_str->callback_buffer_tcp_payload[a].func) && (ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) == ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask && NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask, ndpi_str->callback_buffer_tcp_no_payload[a].excluded_protocol_bitmask) == 0 && NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_no_payload[a].detection_bitmask, detection_bitmask) != 0) { ndpi_str->callback_buffer_tcp_no_payload[a].func(ndpi_str, flow); if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) break; /* Stop after detecting the first protocol */ } } } } /* ********************************************************************************* */ void ndpi_check_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) { if(flow->packet.tcp != NULL) check_ndpi_tcp_flow_func(ndpi_str, flow, ndpi_selection_packet); else if(flow->packet.udp != NULL) check_ndpi_udp_flow_func(ndpi_str, flow, ndpi_selection_packet); else check_ndpi_other_flow_func(ndpi_str, flow, ndpi_selection_packet); } /* ********************************************************************************* */ u_int16_t ndpi_guess_host_protocol_id(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int16_t ret = NDPI_PROTOCOL_UNKNOWN; if(flow->packet.iph) { struct in_addr addr; u_int16_t sport, dport; addr.s_addr = flow->packet.iph->saddr; if((flow->l4_proto == IPPROTO_TCP) && flow->packet.tcp) sport = flow->packet.tcp->source, dport = flow->packet.tcp->dest; else if((flow->l4_proto == IPPROTO_UDP) && flow->packet.udp) sport = flow->packet.udp->source, dport = flow->packet.udp->dest; else sport = dport = 0; /* guess host protocol */ ret = ndpi_network_port_ptree_match(ndpi_str, &addr, sport); if(ret == NDPI_PROTOCOL_UNKNOWN) { addr.s_addr = flow->packet.iph->daddr; ret = ndpi_network_port_ptree_match(ndpi_str, &addr, dport); } } return(ret); } /* ********************************************************************************* */ ndpi_protocol ndpi_detection_giveup(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t enable_guess, u_int8_t *protocol_was_guessed) { ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; *protocol_was_guessed = 0; if(flow == NULL) return(ret); /* Init defaults */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; ret.category = flow->category; /* Ensure that we don't change our mind if detection is already complete */ if((ret.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN)) return(ret); /* TODO: add the remaining stage_XXXX protocols */ if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) { u_int16_t guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN, guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN; if(flow->guessed_protocol_id == NDPI_PROTOCOL_STUN) goto check_stun_export; else if((flow->guessed_protocol_id == NDPI_PROTOCOL_HANGOUT_DUO) || (flow->guessed_protocol_id == NDPI_PROTOCOL_MESSENGER) || (flow->guessed_protocol_id == NDPI_PROTOCOL_WHATSAPP_CALL)) { *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_protocol_id, NDPI_PROTOCOL_UNKNOWN); } else if((flow->l4.tcp.tls.hello_processed == 1) && (flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0')) { *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, NDPI_PROTOCOL_TLS, NDPI_PROTOCOL_UNKNOWN); } else if(enable_guess) { if((flow->guessed_protocol_id == NDPI_PROTOCOL_UNKNOWN) && (flow->packet.l4_protocol == IPPROTO_TCP) && flow->l4.tcp.tls.hello_processed) flow->guessed_protocol_id = NDPI_PROTOCOL_TLS; guessed_protocol_id = flow->guessed_protocol_id, guessed_host_protocol_id = flow->guessed_host_protocol_id; if((guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) && ((flow->packet.l4_protocol == IPPROTO_UDP) && NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_host_protocol_id) && is_udp_guessable_protocol(guessed_host_protocol_id))) flow->guessed_host_protocol_id = guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN; /* Ignore guessed protocol if they have been discarded */ if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) // && (guessed_host_protocol_id == NDPI_PROTOCOL_UNKNOWN) && (flow->packet.l4_protocol == IPPROTO_UDP) && NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_protocol_id) && is_udp_guessable_protocol(guessed_protocol_id)) flow->guessed_protocol_id = guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN; if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) || (guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) { if((guessed_protocol_id == 0) && (flow->protos.stun_ssl.stun.num_binding_requests > 0) && (flow->protos.stun_ssl.stun.num_processed_pkts > 0)) guessed_protocol_id = NDPI_PROTOCOL_STUN; if(flow->host_server_name[0] != '\0') { ndpi_protocol_match_result ret_match; memset(&ret_match, 0, sizeof(ret_match)); ndpi_match_host_subprotocol(ndpi_str, flow, (char *) flow->host_server_name, strlen((const char *) flow->host_server_name), &ret_match, NDPI_PROTOCOL_DNS); if(ret_match.protocol_id != NDPI_PROTOCOL_UNKNOWN) guessed_host_protocol_id = ret_match.protocol_id; } *protocol_was_guessed = 1; ndpi_int_change_protocol(ndpi_str, flow, guessed_host_protocol_id, guessed_protocol_id); } } } else if(enable_guess) { if(flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; flow->detected_protocol_stack[1] = flow->guessed_protocol_id; } if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; flow->detected_protocol_stack[0] = flow->guessed_host_protocol_id; } if(flow->detected_protocol_stack[1] == flow->detected_protocol_stack[0]) { *protocol_was_guessed = 1; flow->detected_protocol_stack[1] = flow->guessed_host_protocol_id; } } if((flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) && (flow->guessed_protocol_id == NDPI_PROTOCOL_STUN)) { check_stun_export: if(flow->protos.stun_ssl.stun.num_processed_pkts || flow->protos.stun_ssl.stun.num_udp_pkts) { // if(/* (flow->protos.stun_ssl.stun.num_processed_pkts >= NDPI_MIN_NUM_STUN_DETECTION) */ *protocol_was_guessed = 1; ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_host_protocol_id, NDPI_PROTOCOL_STUN); } } ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(ret.master_protocol == NDPI_PROTOCOL_STUN) { if(ret.app_protocol == NDPI_PROTOCOL_FACEBOOK) ret.app_protocol = NDPI_PROTOCOL_MESSENGER; else if(ret.app_protocol == NDPI_PROTOCOL_GOOGLE) { /* As Google has recently introduced Duo, we need to distinguish between it and hangout thing that should be handled by the STUN dissector */ ret.app_protocol = NDPI_PROTOCOL_HANGOUT_DUO; } } if(ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) { *protocol_was_guessed = 1; ndpi_fill_protocol_category(ndpi_str, flow, &ret); } return(ret); } /* ********************************************************************************* */ void ndpi_process_extra_packet(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, const unsigned char *packet, const unsigned short packetlen, const u_int64_t current_time_ms, struct ndpi_id_struct *src, struct ndpi_id_struct *dst) { if(flow == NULL) return; if(flow->server_id == NULL) flow->server_id = dst; /* Default */ /* need at least 20 bytes for ip header */ if(packetlen < 20) { return; } flow->packet.current_time_ms = current_time_ms; /* parse packet */ flow->packet.iph = (struct ndpi_iphdr *) packet; /* we are interested in ipv4 packet */ /* set up the packet headers for the extra packet function to use if it wants */ if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0) return; /* detect traffic for tcp or udp only */ flow->src = src, flow->dst = dst; ndpi_connection_tracking(ndpi_str, flow); /* call the extra packet function (which may add more data/info to flow) */ if(flow->extra_packets_func) { if((flow->extra_packets_func(ndpi_str, flow)) == 0) flow->check_extra_packets = 0; if(++flow->num_extra_packets_checked == flow->max_extra_packets_to_check) flow->extra_packets_func = NULL; /* Enough packets detected */ } } /* ********************************************************************************* */ int ndpi_load_ip_category(struct ndpi_detection_module_struct *ndpi_str, const char *ip_address_and_mask, ndpi_protocol_category_t category) { patricia_node_t *node; struct in_addr pin; int bits = 32; char *ptr; char ipbuf[64]; strncpy(ipbuf, ip_address_and_mask, sizeof(ipbuf)); ipbuf[sizeof(ipbuf) - 1] = '\0'; ptr = strrchr(ipbuf, '/'); if(ptr) { *(ptr++) = '\0'; if(atoi(ptr) >= 0 && atoi(ptr) <= 32) bits = atoi(ptr); } if(inet_pton(AF_INET, ipbuf, &pin) != 1) { NDPI_LOG_DBG2(ndpi_str, "Invalid ip/ip+netmask: %s\n", ip_address_and_mask); return(-1); } if((node = add_to_ptree(ndpi_str->custom_categories.ipAddresses_shadow, AF_INET, &pin, bits)) != NULL) { node->value.uv.user_value = (u_int16_t)category, node->value.uv.additional_user_value = 0; } return(0); } /* ********************************************************************************* */ int ndpi_load_hostname_category(struct ndpi_detection_module_struct *ndpi_str, const char *name_to_add, ndpi_protocol_category_t category) { char *name; if(name_to_add == NULL) return(-1); name = ndpi_strdup(name_to_add); if(name == NULL) return(-1); #if 0 printf("===> %s() Loading %s as %u\n", __FUNCTION__, name, category); #endif AC_PATTERN_t ac_pattern; AC_ERROR_t rc; memset(&ac_pattern, 0, sizeof(ac_pattern)); if(ndpi_str->custom_categories.hostnames_shadow.ac_automa == NULL) { free(name); return(-1); } ac_pattern.astring = name, ac_pattern.length = strlen(ac_pattern.astring); ac_pattern.rep.number = (u_int32_t) category, ac_pattern.rep.category = category;; rc = ac_automata_add(ndpi_str->custom_categories.hostnames_shadow.ac_automa, &ac_pattern); if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS) { free(name); return(-1); } if(rc == ACERR_DUPLICATE_PATTERN) free(name); return(0); } /* ********************************************************************************* */ /* Loads an IP or name category */ int ndpi_load_category(struct ndpi_detection_module_struct *ndpi_struct, const char *ip_or_name, ndpi_protocol_category_t category) { int rv; /* Try to load as IP address first */ rv = ndpi_load_ip_category(ndpi_struct, ip_or_name, category); if(rv < 0) { /* IP load failed, load as hostname */ rv = ndpi_load_hostname_category(ndpi_struct, ip_or_name, category); } return(rv); } /* ********************************************************************************* */ int ndpi_enable_loaded_categories(struct ndpi_detection_module_struct *ndpi_str) { int i; /* First add the nDPI known categories matches */ for (i = 0; category_match[i].string_to_match != NULL; i++) ndpi_load_category(ndpi_str, category_match[i].string_to_match, category_match[i].protocol_category); /* Free */ ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa, 1 /* free patterns strings memory */); /* Finalize */ ac_automata_finalize((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa); /* Swap */ ndpi_str->custom_categories.hostnames.ac_automa = ndpi_str->custom_categories.hostnames_shadow.ac_automa; /* Realloc */ ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler); if(ndpi_str->custom_categories.ipAddresses != NULL) ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data); ndpi_str->custom_categories.ipAddresses = ndpi_str->custom_categories.ipAddresses_shadow; ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */); ndpi_str->custom_categories.categories_loaded = 1; return(0); } /* ********************************************************************************* */ int ndpi_fill_ip_protocol_category(struct ndpi_detection_module_struct *ndpi_str, u_int32_t saddr, u_int32_t daddr, ndpi_protocol *ret) { if(ndpi_str->custom_categories.categories_loaded) { prefix_t prefix; patricia_node_t *node; if(saddr == 0) node = NULL; else { /* Make sure all in network byte order otherwise compares wont work */ fill_prefix_v4(&prefix, (struct in_addr *) &saddr, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); } if(!node) { if(daddr != 0) { fill_prefix_v4(&prefix, (struct in_addr *) &daddr, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits); node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix); } } if(node) { ret->category = (ndpi_protocol_category_t) node->value.uv.user_value; return(1); } } ret->category = ndpi_get_proto_category(ndpi_str, *ret); return(0); } /* ********************************************************************************* */ void ndpi_fill_protocol_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol *ret) { if(ndpi_str->custom_categories.categories_loaded) { if(flow->guessed_header_category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) { flow->category = ret->category = flow->guessed_header_category; return; } if(flow->host_server_name[0] != '\0') { u_int32_t id; int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->host_server_name, strlen((char *) flow->host_server_name), &id); if(rc == 0) { flow->category = ret->category = (ndpi_protocol_category_t) id; return; } } if(flow->l4.tcp.tls.hello_processed == 1 && flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0') { u_int32_t id; int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->protos.stun_ssl.ssl.client_requested_server_name, strlen(flow->protos.stun_ssl.ssl.client_requested_server_name), &id); if(rc == 0) { flow->category = ret->category = (ndpi_protocol_category_t) id; return; } } } flow->category = ret->category = ndpi_get_proto_category(ndpi_str, *ret); } /* ********************************************************************************* */ static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL, packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; } /* ********************************************************************************* */ static int ndpi_check_protocol_port_mismatch_exceptions(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_default_ports_tree_node_t *expected_proto, ndpi_protocol *returned_proto) { /* For TLS (and other protocols) it is not simple to guess the exact protocol so before triggering an alert we need to make sure what we have exhausted all the possible options available */ if(returned_proto->master_protocol == NDPI_PROTOCOL_TLS) { switch(expected_proto->proto->protoId) { case NDPI_PROTOCOL_MAIL_IMAPS: case NDPI_PROTOCOL_MAIL_POPS: case NDPI_PROTOCOL_MAIL_SMTPS: return(1); /* This is a reasonable exception */ break; } } return(0); } /* ********************************************************************************* */ static void ndpi_reconcile_protocols(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol *ret) { /* Skype for a host doing MS Teams means MS Teams (MS Teams uses Skype as transport protocol for voice/video) */ if(flow) { /* Do not go for DNS when there is an application protocol. Example DNS.Apple */ if((flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN) && (flow->detected_protocol_stack[0] /* app */ != flow->detected_protocol_stack[1] /* major */)) NDPI_CLR_BIT(flow->risk, NDPI_SUSPICIOUS_DGA_DOMAIN); } switch(ret->app_protocol) { case NDPI_PROTOCOL_MSTEAMS: if(flow->packet.iph && flow->packet.tcp) { // printf("====>> NDPI_PROTOCOL_MSTEAMS\n"); if(ndpi_str->msteams_cache == NULL) ndpi_str->msteams_cache = ndpi_lru_cache_init(1024); if(ndpi_str->msteams_cache) ndpi_lru_add_to_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, (flow->packet.current_time_ms / 1000) & 0xFFFF /* 16 bit */); } break; case NDPI_PROTOCOL_SKYPE: case NDPI_PROTOCOL_SKYPE_CALL: if(flow->packet.iph && flow->packet.udp && ndpi_str->msteams_cache) { u_int16_t when; if(ndpi_lru_find_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, &when, 0 /* Don't remove it as it can be used for other connections */)) { u_int16_t tdiff = ((flow->packet.current_time_ms /1000) & 0xFFFF) - when; if(tdiff < 60 /* sec */) { // printf("====>> NDPI_PROTOCOL_SKYPE(_CALL) -> NDPI_PROTOCOL_MSTEAMS [%u]\n", tdiff); ret->app_protocol = NDPI_PROTOCOL_MSTEAMS; /* Refresh cache */ ndpi_lru_add_to_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr, (flow->packet.current_time_ms / 1000) & 0xFFFF /* 16 bit */); } } } break; } /* switch */ } /* ********************************************************************************* */ ndpi_protocol ndpi_detection_process_packet(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, const unsigned char *packet, const unsigned short packetlen, const u_int64_t current_time_ms, struct ndpi_id_struct *src, struct ndpi_id_struct *dst) { NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_packet; u_int32_t a; ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; if(ndpi_str->ndpi_log_level >= NDPI_LOG_TRACE) NDPI_LOG(flow ? flow->detected_protocol_stack[0] : NDPI_PROTOCOL_UNKNOWN, ndpi_str, NDPI_LOG_TRACE, "START packet processing\n"); if(flow == NULL) return(ret); else ret.category = flow->category; flow->num_processed_pkts++; /* Init default */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(flow->server_id == NULL) flow->server_id = dst; /* Default */ if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) { if(flow->check_extra_packets) { ndpi_process_extra_packet(ndpi_str, flow, packet, packetlen, current_time_ms, src, dst); /* Update in case of new match */ ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0], ret.category = flow->category; goto invalidate_ptr; } else goto ret_protocols; } /* need at least 20 bytes for ip header */ if(packetlen < 20) { /* reset protocol which is normally done in init_packet_header */ ndpi_int_reset_packet_protocol(&flow->packet); goto invalidate_ptr; } flow->packet.current_time_ms = current_time_ms; /* parse packet */ flow->packet.iph = (struct ndpi_iphdr *) packet; /* we are interested in ipv4 packet */ if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0) goto invalidate_ptr; /* detect traffic for tcp or udp only */ flow->src = src, flow->dst = dst; ndpi_connection_tracking(ndpi_str, flow); /* build ndpi_selection packet bitmask */ ndpi_selection_packet = NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC; if(flow->packet.iph != NULL) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IP | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6; if(flow->packet.tcp != NULL) ndpi_selection_packet |= (NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP); if(flow->packet.udp != NULL) ndpi_selection_packet |= (NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP); if(flow->packet.payload_packet_len != 0) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD; if(flow->packet.tcp_retransmission == 0) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_NO_TCP_RETRANSMISSION; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iphv6 != NULL) ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IPV6 | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6; #endif /* NDPI_DETECTION_SUPPORT_IPV6 */ if((!flow->protocol_id_already_guessed) && ( #ifdef NDPI_DETECTION_SUPPORT_IPV6 flow->packet.iphv6 || #endif flow->packet.iph)) { u_int16_t sport, dport; u_int8_t protocol; u_int8_t user_defined_proto; flow->protocol_id_already_guessed = 1; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(flow->packet.iphv6 != NULL) { protocol = flow->packet.iphv6->ip6_hdr.ip6_un1_nxt; } else #endif { protocol = flow->packet.iph->protocol; } if(flow->packet.udp) sport = ntohs(flow->packet.udp->source), dport = ntohs(flow->packet.udp->dest); else if(flow->packet.tcp) sport = ntohs(flow->packet.tcp->source), dport = ntohs(flow->packet.tcp->dest); else sport = dport = 0; /* guess protocol */ flow->guessed_protocol_id = (int16_t) ndpi_guess_protocol_id(ndpi_str, flow, protocol, sport, dport, &user_defined_proto); flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow); if(ndpi_str->custom_categories.categories_loaded && flow->packet.iph) { ndpi_fill_ip_protocol_category(ndpi_str, flow->packet.iph->saddr, flow->packet.iph->daddr, &ret); flow->guessed_header_category = ret.category; } else flow->guessed_header_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED; if(flow->guessed_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) { /* This is a custom protocol and it has priority over everything else */ ret.master_protocol = NDPI_PROTOCOL_UNKNOWN, ret.app_protocol = flow->guessed_protocol_id ? flow->guessed_protocol_id : flow->guessed_host_protocol_id; ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } if(user_defined_proto && flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) { if(flow->packet.iph) { if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { u_int8_t protocol_was_guessed; /* ret.master_protocol = flow->guessed_protocol_id , ret.app_protocol = flow->guessed_host_protocol_id; /\* ****** *\/ */ ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed); } ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } } else { /* guess host protocol */ if(flow->packet.iph) { flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow); /* We could implement a shortcut here skipping dissectors for protocols we have identified by other means such as with the IP However we do NOT stop here and skip invoking the dissectors because we want to dissect the flow (e.g. dissect the TLS) and extract metadata. */ #if SKIP_INVOKING_THE_DISSECTORS if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) { /* We have identified a protocol using the IP address so it is not worth to dissect the traffic as we already have the solution */ ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id; } #endif } } } if(flow->guessed_host_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) { /* This is a custom protocol and it has priority over everything else */ ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id; ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet); ndpi_fill_protocol_category(ndpi_str, flow, &ret); goto invalidate_ptr; } ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet); a = flow->packet.detected_protocol_stack[0]; if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_str->detection_bitmask, a) == 0) a = NDPI_PROTOCOL_UNKNOWN; if(a != NDPI_PROTOCOL_UNKNOWN) { int i; for (i = 0; i < sizeof(flow->host_server_name); i++) { if(flow->host_server_name[i] != '\0') flow->host_server_name[i] = tolower(flow->host_server_name[i]); else { flow->host_server_name[i] = '\0'; break; } } } ret_protocols: if(flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN) { ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0]; if(ret.app_protocol == ret.master_protocol) ret.master_protocol = NDPI_PROTOCOL_UNKNOWN; } else ret.app_protocol = flow->detected_protocol_stack[0]; /* Don't overwrite the category if already set */ if((flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN)) ndpi_fill_protocol_category(ndpi_str, flow, &ret); else ret.category = flow->category; if((flow->num_processed_pkts == 1) && (ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol == NDPI_PROTOCOL_UNKNOWN) && flow->packet.tcp && (flow->packet.tcp->syn == 0) && (flow->guessed_protocol_id == 0)) { u_int8_t protocol_was_guessed; /* This is a TCP flow - whose first packet is NOT a SYN - no protocol has been detected We don't see how future packets can match anything hence we giveup here */ ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed); } if((ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) && (flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) { ret.master_protocol = ret.app_protocol; ret.app_protocol = flow->guessed_host_protocol_id; } if((!flow->risk_checked) && (ret.master_protocol != NDPI_PROTOCOL_UNKNOWN)) { ndpi_default_ports_tree_node_t *found; u_int16_t *default_ports, sport, dport; if(flow->packet.udp) found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_UDP, sport = ntohs(flow->packet.udp->source), dport = ntohs(flow->packet.udp->dest)), default_ports = ndpi_str->proto_defaults[ret.master_protocol].udp_default_ports; else if(flow->packet.tcp) found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_TCP, sport = ntohs(flow->packet.tcp->source), dport = ntohs(flow->packet.tcp->dest)), default_ports = ndpi_str->proto_defaults[ret.master_protocol].tcp_default_ports; else found = NULL, default_ports = NULL; if(found && (found->proto->protoId != NDPI_PROTOCOL_UNKNOWN) && (found->proto->protoId != ret.master_protocol)) { // printf("******** %u / %u\n", found->proto->protoId, ret.master_protocol); if(!ndpi_check_protocol_port_mismatch_exceptions(ndpi_str, flow, found, &ret)) NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT); } else if(default_ports && (default_ports[0] != 0)) { u_int8_t found = 0, i; for(i=0; (i<MAX_DEFAULT_PORTS) && (default_ports[i] != 0); i++) { if((default_ports[i] == sport) || (default_ports[i] == dport)) { found = 1; break; } } /* for */ if(!found) { // printf("******** Invalid default port\n"); NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT); } } flow->risk_checked = 1; } ndpi_reconcile_protocols(ndpi_str, flow, &ret); invalidate_ptr: /* Invalidate packet memory to avoid accessing the pointers below when the packet is no longer accessible */ flow->packet.iph = NULL, flow->packet.tcp = NULL, flow->packet.udp = NULL, flow->packet.payload = NULL; ndpi_reset_packet_line_info(&flow->packet); return(ret); } /* ********************************************************************************* */ u_int32_t ndpi_bytestream_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; val = 0; // cancel if eof, ' ' or line end chars are reached while (*str >= '0' && *str <= '9' && max_chars_to_read > 0) { val *= 10; val += *str - '0'; str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } return(val); } /* ********************************************************************************* */ #ifdef CODE_UNUSED u_int32_t ndpi_bytestream_dec_or_hex_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; val = 0; if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') { return(ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read)); } else { /*use base 16 system */ str += 2; max_chars_to_read -= 2; *bytes_read = *bytes_read + 2; while (max_chars_to_read > 0) { if(*str >= '0' && *str <= '9') { val *= 16; val += *str - '0'; } else if(*str >= 'a' && *str <= 'f') { val *= 16; val += *str + 10 - 'a'; } else if(*str >= 'A' && *str <= 'F') { val *= 16; val += *str + 10 - 'A'; } else { break; } str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } } return(val); } #endif /* ********************************************************************************* */ u_int64_t ndpi_bytestream_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int64_t val; val = 0; // cancel if eof, ' ' or line end chars are reached while (max_chars_to_read > 0 && *str >= '0' && *str <= '9') { val *= 10; val += *str - '0'; str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } return(val); } /* ********************************************************************************* */ u_int64_t ndpi_bytestream_dec_or_hex_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int64_t val; val = 0; if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') { return(ndpi_bytestream_to_number64(str, max_chars_to_read, bytes_read)); } else { /*use base 16 system */ str += 2; max_chars_to_read -= 2; *bytes_read = *bytes_read + 2; while (max_chars_to_read > 0) { if(*str >= '0' && *str <= '9') { val *= 16; val += *str - '0'; } else if(*str >= 'a' && *str <= 'f') { val *= 16; val += *str + 10 - 'a'; } else if(*str >= 'A' && *str <= 'F') { val *= 16; val += *str + 10 - 'A'; } else { break; } str++; max_chars_to_read = max_chars_to_read - 1; *bytes_read = *bytes_read + 1; } } return(val); } /* ********************************************************************************* */ u_int32_t ndpi_bytestream_to_ipv4(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int32_t val; u_int16_t read = 0; u_int16_t oldread; u_int32_t c; /* ip address must be X.X.X.X with each X between 0 and 255 */ oldread = read; c = ndpi_bytestream_to_number(str, max_chars_to_read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = c << 24; oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = val + (c << 16); oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.') return(0); read++; val = val + (c << 8); oldread = read; c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read); if(c > 255 || oldread == read || max_chars_to_read == read) return(0); val = val + c; *bytes_read = *bytes_read + read; return(htonl(val)); } /* ********************************************************************************* */ /* internal function for every detection to parse one packet and to increase the info buffer */ void ndpi_parse_packet_line_info(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int32_t a; struct ndpi_packet_struct *packet = &flow->packet; if((packet->payload_packet_len < 3) || (packet->payload == NULL)) return; if(packet->packet_lines_parsed_complete != 0) return; packet->packet_lines_parsed_complete = 1; ndpi_reset_packet_line_info(packet); packet->line[packet->parsed_lines].ptr = packet->payload; packet->line[packet->parsed_lines].len = 0; for (a = 0; ((a+1) < packet->payload_packet_len) && (packet->parsed_lines < NDPI_MAX_PARSE_LINES_PER_PACKET); a++) { if((packet->payload[a] == 0x0d) && (packet->payload[a+1] == 0x0a)) { /* If end of line char sequence CR+NL "\r\n", process line */ if(((a + 3) < packet->payload_packet_len) && (packet->payload[a+2] == 0x0d) && (packet->payload[a+3] == 0x0a)) { /* \r\n\r\n */ int diff; /* No unsigned ! */ u_int32_t a1 = a + 4; diff = packet->payload_packet_len - a1; if(diff > 0) { diff = ndpi_min(diff, sizeof(flow->initial_binary_bytes)); memcpy(&flow->initial_binary_bytes, &packet->payload[a1], diff); flow->initial_binary_bytes_len = diff; } } packet->line[packet->parsed_lines].len = (u_int16_t)(((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); /* First line of a HTTP response parsing. Expected a "HTTP/1.? ???" */ if(packet->parsed_lines == 0 && packet->line[0].len >= NDPI_STATICSTRING_LEN("HTTP/1.X 200 ") && strncasecmp((const char *) packet->line[0].ptr, "HTTP/1.", NDPI_STATICSTRING_LEN("HTTP/1.")) == 0 && packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] > '0' && /* response code between 000 and 699 */ packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] < '6') { packet->http_response.ptr = &packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.1 ")]; packet->http_response.len = packet->line[0].len - NDPI_STATICSTRING_LEN("HTTP/1.1 "); packet->http_num_headers++; /* Set server HTTP response code */ if(packet->payload_packet_len >= 12) { char buf[4]; /* Set server HTTP response code */ strncpy(buf, (char *) &packet->payload[9], 3); buf[3] = '\0'; flow->http.response_status_code = atoi(buf); /* https://en.wikipedia.org/wiki/List_of_HTTP_status_codes */ if((flow->http.response_status_code < 100) || (flow->http.response_status_code > 509)) flow->http.response_status_code = 0; /* Out of range */ } } /* "Server:" header line in HTTP response */ if(packet->line[packet->parsed_lines].len > NDPI_STATICSTRING_LEN("Server:") + 1 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Server:", NDPI_STATICSTRING_LEN("Server:")) == 0) { // some stupid clients omit a space and place the servername directly after the colon if(packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")] == ' ') { packet->server_line.ptr = &packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:") + 1]; packet->server_line.len = packet->line[packet->parsed_lines].len - (NDPI_STATICSTRING_LEN("Server:") + 1); } else { packet->server_line.ptr = &packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")]; packet->server_line.len = packet->line[packet->parsed_lines].len - NDPI_STATICSTRING_LEN("Server:"); } packet->http_num_headers++; } /* "Host:" header line in HTTP request */ if(packet->line[packet->parsed_lines].len > 6 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Host:", 5) == 0) { // some stupid clients omit a space and place the hostname directly after the colon if(packet->line[packet->parsed_lines].ptr[5] == ' ') { packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[6]; packet->host_line.len = packet->line[packet->parsed_lines].len - 6; } else { packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[5]; packet->host_line.len = packet->line[packet->parsed_lines].len - 5; } packet->http_num_headers++; } /* "X-Forwarded-For:" header line in HTTP request. Commonly used for HTTP proxies. */ if(packet->line[packet->parsed_lines].len > 17 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Forwarded-For:", 16) == 0) { // some stupid clients omit a space and place the hostname directly after the colon if(packet->line[packet->parsed_lines].ptr[16] == ' ') { packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[17]; packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 17; } else { packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 16; } packet->http_num_headers++; } /* "Content-Type:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 14 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Type: ", 14) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type: ", 14) == 0)) { packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[14]; packet->content_line.len = packet->line[packet->parsed_lines].len - 14; while ((packet->content_line.len > 0) && (packet->content_line.ptr[0] == ' ')) packet->content_line.len--, packet->content_line.ptr++; packet->http_num_headers++; } /* "Content-Type:" header line in HTTP AGAIN. Probably a bogus response without space after ":" */ if((packet->content_line.len == 0) && (packet->line[packet->parsed_lines].len > 13) && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type:", 13) == 0)) { packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[13]; packet->content_line.len = packet->line[packet->parsed_lines].len - 13; packet->http_num_headers++; } if(packet->content_line.len > 0) { /* application/json; charset=utf-8 */ char separator[] = {';', '\r', '\0'}; int i; for (i = 0; separator[i] != '\0'; i++) { char *c = memchr((char *) packet->content_line.ptr, separator[i], packet->content_line.len); if(c != NULL) packet->content_line.len = c - (char *) packet->content_line.ptr; } } /* "Accept:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept: ", 8) == 0) { packet->accept_line.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->accept_line.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "Referer:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 9 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Referer: ", 9) == 0) { packet->referer_line.ptr = &packet->line[packet->parsed_lines].ptr[9]; packet->referer_line.len = packet->line[packet->parsed_lines].len - 9; packet->http_num_headers++; } /* "User-Agent:" header line in HTTP request. */ if(packet->line[packet->parsed_lines].len > 12 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-Agent: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-agent: ", 12) == 0)) { packet->user_agent_line.ptr = &packet->line[packet->parsed_lines].ptr[12]; packet->user_agent_line.len = packet->line[packet->parsed_lines].len - 12; packet->http_num_headers++; } /* "Content-Encoding:" header line in HTTP response (and request?). */ if(packet->line[packet->parsed_lines].len > 18 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Encoding: ", 18) == 0) { packet->http_encoding.ptr = &packet->line[packet->parsed_lines].ptr[18]; packet->http_encoding.len = packet->line[packet->parsed_lines].len - 18; packet->http_num_headers++; } /* "Transfer-Encoding:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 19 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Transfer-Encoding: ", 19) == 0) { packet->http_transfer_encoding.ptr = &packet->line[packet->parsed_lines].ptr[19]; packet->http_transfer_encoding.len = packet->line[packet->parsed_lines].len - 19; packet->http_num_headers++; } /* "Content-Length:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 16 && ((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Length: ", 16) == 0) || (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "content-length: ", 16) == 0))) { packet->http_contentlen.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->http_contentlen.len = packet->line[packet->parsed_lines].len - 16; packet->http_num_headers++; } /* "Content-Disposition"*/ if(packet->line[packet->parsed_lines].len > 21 && ((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Disposition: ", 21) == 0))) { packet->content_disposition_line.ptr = &packet->line[packet->parsed_lines].ptr[21]; packet->content_disposition_line.len = packet->line[packet->parsed_lines].len - 21; packet->http_num_headers++; } /* "Cookie:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Cookie: ", 8) == 0) { packet->http_cookie.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->http_cookie.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "Origin:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Origin: ", 8) == 0) { packet->http_origin.ptr = &packet->line[packet->parsed_lines].ptr[8]; packet->http_origin.len = packet->line[packet->parsed_lines].len - 8; packet->http_num_headers++; } /* "X-Session-Type:" header line in HTTP. */ if(packet->line[packet->parsed_lines].len > 16 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Session-Type: ", 16) == 0) { packet->http_x_session_type.ptr = &packet->line[packet->parsed_lines].ptr[16]; packet->http_x_session_type.len = packet->line[packet->parsed_lines].len - 16; packet->http_num_headers++; } /* Identification and counting of other HTTP headers. * We consider the most common headers, but there are many others, * which can be seen at references below: * - https://tools.ietf.org/html/rfc7230 * - https://en.wikipedia.org/wiki/List_of_HTTP_header_fields */ if((packet->line[packet->parsed_lines].len > 6 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Date: ", 6) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Vary: ", 6) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "ETag: ", 6) == 0)) || (packet->line[packet->parsed_lines].len > 8 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Pragma: ", 8) == 0) || (packet->line[packet->parsed_lines].len > 9 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Expires: ", 9) == 0) || (packet->line[packet->parsed_lines].len > 12 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Set-Cookie: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Keep-Alive: ", 12) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Connection: ", 12) == 0)) || (packet->line[packet->parsed_lines].len > 15 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Last-Modified: ", 15) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Ranges: ", 15) == 0)) || (packet->line[packet->parsed_lines].len > 17 && (strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Language: ", 17) == 0 || strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Encoding: ", 17) == 0)) || (packet->line[packet->parsed_lines].len > 27 && strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Upgrade-Insecure-Requests: ", 27) == 0)) { /* Just count. In the future, if needed, this if can be splited to parse these headers */ packet->http_num_headers++; } if(packet->line[packet->parsed_lines].len == 0) { packet->empty_line_position = a; packet->empty_line_position_set = 1; } if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1)) return; packet->parsed_lines++; packet->line[packet->parsed_lines].ptr = &packet->payload[a + 2]; packet->line[packet->parsed_lines].len = 0; a++; /* next char in the payload */ } } if(packet->parsed_lines >= 1) { packet->line[packet->parsed_lines].len = (u_int16_t)(((unsigned long) &packet->payload[packet->payload_packet_len]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); packet->parsed_lines++; } } /* ********************************************************************************* */ void ndpi_parse_packet_line_info_any(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t a; u_int16_t end = packet->payload_packet_len; if(packet->packet_lines_parsed_complete != 0) return; packet->packet_lines_parsed_complete = 1; packet->parsed_lines = 0; if(packet->payload_packet_len == 0) return; packet->line[packet->parsed_lines].ptr = packet->payload; packet->line[packet->parsed_lines].len = 0; for (a = 0; a < end; a++) { if(packet->payload[a] == 0x0a) { packet->line[packet->parsed_lines].len = (u_int16_t)( ((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr)); if(a > 0 && packet->payload[a - 1] == 0x0d) packet->line[packet->parsed_lines].len--; if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1)) break; packet->parsed_lines++; packet->line[packet->parsed_lines].ptr = &packet->payload[a + 1]; packet->line[packet->parsed_lines].len = 0; if((a + 1) >= packet->payload_packet_len) break; //a++; } } } /* ********************************************************************************* */ u_int16_t ndpi_check_for_email_address(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t counter) { struct ndpi_packet_struct *packet = &flow->packet; NDPI_LOG_DBG2(ndpi_str, "called ndpi_check_for_email_address\n"); if(packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_')) { NDPI_LOG_DBG2(ndpi_str, "first letter\n"); counter++; while (packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_' || packet->payload[counter] == '.')) { NDPI_LOG_DBG2(ndpi_str, "further letter\n"); counter++; if(packet->payload_packet_len > counter && packet->payload[counter] == '@') { NDPI_LOG_DBG2(ndpi_str, "@\n"); counter++; while (packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') || (packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') || (packet->payload[counter] >= '0' && packet->payload[counter] <= '9') || packet->payload[counter] == '-' || packet->payload[counter] == '_')) { NDPI_LOG_DBG2(ndpi_str, "letter\n"); counter++; if(packet->payload_packet_len > counter && packet->payload[counter] == '.') { NDPI_LOG_DBG2(ndpi_str, ".\n"); counter++; if(packet->payload_packet_len > counter + 1 && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') && (packet->payload[counter + 1] >= 'a' && packet->payload[counter + 1] <= 'z'))) { NDPI_LOG_DBG2(ndpi_str, "two letters\n"); counter += 2; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace1\n"); return(counter); } else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') { NDPI_LOG_DBG2(ndpi_str, "one letter\n"); counter++; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace2\n"); return(counter); } else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') { counter++; if(packet->payload_packet_len > counter && (packet->payload[counter] == ' ' || packet->payload[counter] == ';')) { NDPI_LOG_DBG2(ndpi_str, "whitespace3\n"); return(counter); } else { return(0); } } else { return(0); } } else { return(0); } } else { return(0); } } } return(0); } } } return(0); } #ifdef NDPI_ENABLE_DEBUG_MESSAGES /* ********************************************************************************* */ void ndpi_debug_get_last_log_function_line(struct ndpi_detection_module_struct *ndpi_str, const char **file, const char **func, u_int32_t *line) { *file = ""; *func = ""; if(ndpi_str->ndpi_debug_print_file != NULL) *file = ndpi_str->ndpi_debug_print_file; if(ndpi_str->ndpi_debug_print_function != NULL) *func = ndpi_str->ndpi_debug_print_function; *line = ndpi_str->ndpi_debug_print_line; } #endif /* ********************************************************************************* */ u_int8_t ndpi_detection_get_l4(const u_int8_t *l3, u_int16_t l3_len, const u_int8_t **l4_return, u_int16_t *l4_len_return, u_int8_t *l4_protocol_return, u_int32_t flags) { return(ndpi_detection_get_l4_internal(NULL, l3, l3_len, l4_return, l4_len_return, l4_protocol_return, flags)); } /* ********************************************************************************* */ void ndpi_set_detected_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { struct ndpi_id_struct *src = flow->src, *dst = flow->dst; ndpi_int_change_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); if(src != NULL) { NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, upper_detected_protocol); if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN) NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, lower_detected_protocol); } if(dst != NULL) { NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, upper_detected_protocol); if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN) NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, lower_detected_protocol); } } /* ********************************************************************************* */ u_int16_t ndpi_get_flow_masterprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { return(flow->detected_protocol_stack[1]); } /* ********************************************************************************* */ void ndpi_int_change_flow_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { if(!flow) return; flow->detected_protocol_stack[0] = upper_detected_protocol, flow->detected_protocol_stack[1] = lower_detected_protocol; } /* ********************************************************************************* */ void ndpi_int_change_packet_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { struct ndpi_packet_struct *packet = &flow->packet; /* NOTE: everything below is identically to change_flow_protocol * except flow->packet If you want to change something here, * don't! Change it for the flow function and apply it here * as well */ if(!packet) return; packet->detected_protocol_stack[0] = upper_detected_protocol, packet->detected_protocol_stack[1] = lower_detected_protocol; } /* ********************************************************************************* */ /* generic function for changing the protocol * * what it does is: * 1.update the flow protocol stack with the new protocol * 2.update the packet protocol stack with the new protocol */ void ndpi_int_change_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) { if((upper_detected_protocol == NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN)) upper_detected_protocol = lower_detected_protocol; if(upper_detected_protocol == lower_detected_protocol) lower_detected_protocol = NDPI_PROTOCOL_UNKNOWN; if((upper_detected_protocol != NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol == NDPI_PROTOCOL_UNKNOWN)) { if((flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (upper_detected_protocol != flow->guessed_host_protocol_id)) { if(ndpi_str->proto_defaults[upper_detected_protocol].can_have_a_subprotocol) { lower_detected_protocol = upper_detected_protocol; upper_detected_protocol = flow->guessed_host_protocol_id; } } } ndpi_int_change_flow_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); ndpi_int_change_packet_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol); } /* ********************************************************************************* */ void ndpi_int_change_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, ndpi_protocol_category_t protocol_category) { flow->category = protocol_category; } /* ********************************************************************************* */ /* turns a packet back to unknown */ void ndpi_int_reset_packet_protocol(struct ndpi_packet_struct *packet) { int a; for (a = 0; a < NDPI_PROTOCOL_SIZE; a++) packet->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN; } /* ********************************************************************************* */ void ndpi_int_reset_protocol(struct ndpi_flow_struct *flow) { if(flow) { int a; for (a = 0; a < NDPI_PROTOCOL_SIZE; a++) flow->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN; } } /* ********************************************************************************* */ void NDPI_PROTOCOL_IP_clear(ndpi_ip_addr_t *ip) { memset(ip, 0, sizeof(ndpi_ip_addr_t)); } /* ********************************************************************************* */ #ifdef CODE_UNUSED /* NTOP */ int NDPI_PROTOCOL_IP_is_set(const ndpi_ip_addr_t *ip) { return(memcmp(ip, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(ndpi_ip_addr_t)) != 0); } #endif /* ********************************************************************************* */ /* check if the source ip address in packet and ip are equal */ /* NTOP */ int ndpi_packet_src_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { if(packet->iphv6->ip6_src.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] && packet->iphv6->ip6_src.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] && packet->iphv6->ip6_src.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] && packet->iphv6->ip6_src.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3]) return(1); //else return(0); } #endif /* IPv4 */ if(packet->iph->saddr == ip->ipv4) return(1); return(0); } /* ********************************************************************************* */ /* check if the destination ip address in packet and ip are equal */ int ndpi_packet_dst_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { if(packet->iphv6->ip6_dst.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] && packet->iphv6->ip6_dst.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3]) return(1); //else return(0); } #endif /* IPv4 */ if(packet->iph->saddr == ip->ipv4) return(1); return(0); } /* ********************************************************************************* */ /* get the source ip address from packet and put it into ip */ /* NTOP */ void ndpi_packet_src_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) { NDPI_PROTOCOL_IP_clear(ip); #ifdef NDPI_DETECTION_SUPPORT_IPV6 /* IPv6 */ if(packet->iphv6 != NULL) { ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_src.u6_addr.u6_addr32[0]; ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_src.u6_addr.u6_addr32[1]; ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_src.u6_addr.u6_addr32[2]; ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_src.u6_addr.u6_addr32[3]; } else #endif /* IPv4 */ ip->ipv4 = packet->iph->saddr; } /* ********************************************************************************* */ /* get the destination ip address from packet and put it into ip */ /* NTOP */ void ndpi_packet_dst_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) { NDPI_PROTOCOL_IP_clear(ip); #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(packet->iphv6 != NULL) { ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[0]; ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[1]; ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[2]; ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[3]; } else #endif ip->ipv4 = packet->iph->daddr; } /* ********************************************************************************* */ u_int8_t ndpi_is_ipv6(const ndpi_ip_addr_t *ip) { #ifdef NDPI_DETECTION_SUPPORT_IPV6 return(ip->ipv6.u6_addr.u6_addr32[1] != 0 || ip->ipv6.u6_addr.u6_addr32[2] != 0 || ip->ipv6.u6_addr.u6_addr32[3] != 0); #else return(0); #endif } /* ********************************************************************************* */ char *ndpi_get_ip_string(const ndpi_ip_addr_t *ip, char *buf, u_int buf_len) { const u_int8_t *a = (const u_int8_t *) &ip->ipv4; #ifdef NDPI_DETECTION_SUPPORT_IPV6 if(ndpi_is_ipv6(ip)) { if(inet_ntop(AF_INET6, &ip->ipv6.u6_addr, buf, buf_len) == NULL) buf[0] = '\0'; return(buf); } #endif snprintf(buf, buf_len, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]); return(buf); } /* ****************************************************** */ /* Returns -1 on failutre, otherwise fills parsed_ip and returns the IP version */ int ndpi_parse_ip_string(const char *ip_str, ndpi_ip_addr_t *parsed_ip) { int rv = -1; memset(parsed_ip, 0, sizeof(*parsed_ip)); if(strchr(ip_str, '.')) { if(inet_pton(AF_INET, ip_str, &parsed_ip->ipv4) > 0) rv = 4; #ifdef NDPI_DETECTION_SUPPORT_IPV6 } else { if(inet_pton(AF_INET6, ip_str, &parsed_ip->ipv6) > 0) rv = 6; #endif } return(rv); } /* ****************************************************** */ u_int16_t ntohs_ndpi_bytestream_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) { u_int16_t val = ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read); return(ntohs(val)); } /* ****************************************************** */ u_int8_t ndpi_is_proto(ndpi_protocol proto, u_int16_t p) { return(((proto.app_protocol == p) || (proto.master_protocol == p)) ? 1 : 0); } /* ****************************************************** */ u_int16_t ndpi_get_lower_proto(ndpi_protocol proto) { return((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) ? proto.master_protocol : proto.app_protocol); } /* ****************************************************** */ ndpi_protocol ndpi_guess_undetected_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, u_int8_t proto, u_int32_t shost /* host byte order */, u_int16_t sport, u_int32_t dhost /* host byte order */, u_int16_t dport) { u_int32_t rc; struct in_addr addr; ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED}; u_int8_t user_defined_proto; if((proto == IPPROTO_TCP) || (proto == IPPROTO_UDP)) { rc = ndpi_search_tcp_or_udp_raw(ndpi_str, flow, proto, shost, dhost, sport, dport); if(rc != NDPI_PROTOCOL_UNKNOWN) { if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc)) ; else { ret.app_protocol = rc, ret.master_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); if(ret.app_protocol == ret.master_protocol) ret.master_protocol = NDPI_PROTOCOL_UNKNOWN; ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } } rc = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); if(rc != NDPI_PROTOCOL_UNKNOWN) { if(flow && (proto == IPPROTO_UDP) && NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc)) ; else { ret.app_protocol = rc; if(rc == NDPI_PROTOCOL_TLS) goto check_guessed_skype; else { ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } } } check_guessed_skype: addr.s_addr = htonl(shost); if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE) { ret.app_protocol = NDPI_PROTOCOL_SKYPE; } else { addr.s_addr = htonl(dhost); if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE) ret.app_protocol = NDPI_PROTOCOL_SKYPE; } } else ret.app_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto); ret.category = ndpi_get_proto_category(ndpi_str, ret); return(ret); } /* ****************************************************** */ char *ndpi_protocol2id(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto, char *buf, u_int buf_len) { if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) { if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN) snprintf(buf, buf_len, "%u.%u", proto.master_protocol, proto.app_protocol); else snprintf(buf, buf_len, "%u", proto.master_protocol); } else snprintf(buf, buf_len, "%u", proto.app_protocol); return(buf); } /* ****************************************************** */ char *ndpi_protocol2name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto, char *buf, u_int buf_len) { if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) { if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN) snprintf(buf, buf_len, "%s.%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol), ndpi_get_proto_name(ndpi_str, proto.app_protocol)); else snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol)); } else snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.app_protocol)); return(buf); } /* ****************************************************** */ int ndpi_is_custom_category(ndpi_protocol_category_t category) { switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: return(1); break; default: return(0); break; } } /* ****************************************************** */ void ndpi_category_set_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_category_t category, char *name) { if(!name) return; switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: snprintf(ndpi_str->custom_category_labels[0], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: snprintf(ndpi_str->custom_category_labels[1], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: snprintf(ndpi_str->custom_category_labels[2], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: snprintf(ndpi_str->custom_category_labels[3], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: snprintf(ndpi_str->custom_category_labels[4], CUSTOM_CATEGORY_LABEL_LEN, "%s", name); break; default: break; } } /* ****************************************************** */ const char *ndpi_category_get_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_category_t category) { if((!ndpi_str) || (category >= NDPI_PROTOCOL_NUM_CATEGORIES)) { static char b[24]; if(!ndpi_str) snprintf(b, sizeof(b), "NULL nDPI"); else snprintf(b, sizeof(b), "Invalid category %d", (int) category); return(b); } if((category >= NDPI_PROTOCOL_CATEGORY_CUSTOM_1) && (category <= NDPI_PROTOCOL_CATEGORY_CUSTOM_5)) { switch (category) { case NDPI_PROTOCOL_CATEGORY_CUSTOM_1: return(ndpi_str->custom_category_labels[0]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_2: return(ndpi_str->custom_category_labels[1]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_3: return(ndpi_str->custom_category_labels[2]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_4: return(ndpi_str->custom_category_labels[3]); case NDPI_PROTOCOL_CATEGORY_CUSTOM_5: return(ndpi_str->custom_category_labels[4]); case NDPI_PROTOCOL_NUM_CATEGORIES: return("Code should not use this internal constant"); default: return("Unspecified"); } } else return(categories[category]); } /* ****************************************************** */ ndpi_protocol_category_t ndpi_get_proto_category(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol proto) { if(proto.category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) return(proto.category); /* simple rule: sub protocol first, master after */ else if((proto.master_protocol == NDPI_PROTOCOL_UNKNOWN) || (ndpi_str->proto_defaults[proto.app_protocol].protoCategory != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) { if(proto.app_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) return(ndpi_str->proto_defaults[proto.app_protocol].protoCategory); } else if(proto.master_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) return(ndpi_str->proto_defaults[proto.master_protocol].protoCategory); return(NDPI_PROTOCOL_CATEGORY_UNSPECIFIED); } /* ****************************************************** */ char *ndpi_get_proto_name(struct ndpi_detection_module_struct *ndpi_str, u_int16_t proto_id) { if((proto_id >= ndpi_str->ndpi_num_supported_protocols) || (proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) || (ndpi_str->proto_defaults[proto_id].protoName == NULL)) proto_id = NDPI_PROTOCOL_UNKNOWN; return(ndpi_str->proto_defaults[proto_id].protoName); } /* ****************************************************** */ ndpi_protocol_breed_t ndpi_get_proto_breed(struct ndpi_detection_module_struct *ndpi_str, u_int16_t proto_id) { if((proto_id >= ndpi_str->ndpi_num_supported_protocols) || (proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) || (ndpi_str->proto_defaults[proto_id].protoName == NULL)) proto_id = NDPI_PROTOCOL_UNKNOWN; return(ndpi_str->proto_defaults[proto_id].protoBreed); } /* ****************************************************** */ char *ndpi_get_proto_breed_name(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_breed_t breed_id) { switch (breed_id) { case NDPI_PROTOCOL_SAFE: return("Safe"); break; case NDPI_PROTOCOL_ACCEPTABLE: return("Acceptable"); break; case NDPI_PROTOCOL_FUN: return("Fun"); break; case NDPI_PROTOCOL_UNSAFE: return("Unsafe"); break; case NDPI_PROTOCOL_POTENTIALLY_DANGEROUS: return("Potentially Dangerous"); break; case NDPI_PROTOCOL_DANGEROUS: return("Dangerous"); break; case NDPI_PROTOCOL_UNRATED: default: return("Unrated"); break; } } /* ****************************************************** */ int ndpi_get_protocol_id(struct ndpi_detection_module_struct *ndpi_str, char *proto) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) if(strcasecmp(proto, ndpi_str->proto_defaults[i].protoName) == 0) return(i); return(-1); } /* ****************************************************** */ int ndpi_get_category_id(struct ndpi_detection_module_struct *ndpi_str, char *cat) { int i; for (i = 0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) { const char *name = ndpi_category_get_name(ndpi_str, i); if(strcasecmp(cat, name) == 0) return(i); } return(-1); } /* ****************************************************** */ void ndpi_dump_protocols(struct ndpi_detection_module_struct *ndpi_str) { int i; for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) printf("%3d %-22s %-8s %-12s %s\n", i, ndpi_str->proto_defaults[i].protoName, ndpi_get_l4_proto_name(ndpi_get_l4_proto_info(ndpi_str, i)), ndpi_get_proto_breed_name(ndpi_str, ndpi_str->proto_defaults[i].protoBreed), ndpi_category_get_name(ndpi_str, ndpi_str->proto_defaults[i].protoCategory)); } /* ****************************************************** */ /* * Find the first occurrence of find in s, where the search is limited to the * first slen characters of s. */ char *ndpi_strnstr(const char *s, const char *find, size_t slen) { char c; size_t len; if((c = *find++) != '\0') { len = strnlen(find, slen); do { char sc; do { if(slen-- < 1 || (sc = *s++) == '\0') return(NULL); } while (sc != c); if(len > slen) return(NULL); } while (strncmp(s, find, len) != 0); s--; } return((char *) s); } /* ****************************************************** */ /* * Same as ndpi_strnstr but case-insensitive */ const char * ndpi_strncasestr(const char *str1, const char *str2, size_t len) { size_t str1_len = strnlen(str1, len); size_t str2_len = strlen(str2); size_t i; for(i = 0; i < (str1_len - str2_len + 1); i++){ if(str1[0] == '\0') return NULL; else if(strncasecmp(str1, str2, str2_len) == 0) return(str1); str1++; } return NULL; } /* ****************************************************** */ int ndpi_match_prefix(const u_int8_t *payload, size_t payload_len, const char *str, size_t str_len) { int rc = str_len <= payload_len ? memcmp(payload, str, str_len) == 0 : 0; return(rc); } /* ****************************************************** */ int ndpi_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int8_t is_host_match) { AC_TEXT_t ac_input_text; ndpi_automa *automa = is_host_match ? &ndpi_str->host_automa : &ndpi_str->content_automa; AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED}; int rc; if((automa->ac_automa == NULL) || (string_to_match_len == 0)) return(NDPI_PROTOCOL_UNKNOWN); if(!automa->ac_automa_finalized) { printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__); return(0); /* No matches */ } ac_input_text.astring = string_to_match, ac_input_text.length = string_to_match_len; rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; /* We need to take into account also rc == 0 that is used for partial matches */ ret_match->protocol_id = match.number, ret_match->protocol_category = match.category, ret_match->protocol_breed = match.breed; return(rc ? match.number : 0); } /* **************************************** */ static u_int8_t ndpi_is_more_generic_protocol(u_int16_t previous_proto, u_int16_t new_proto) { /* Sometimes certificates are more generic than previously identified protocols */ if((previous_proto == NDPI_PROTOCOL_UNKNOWN) || (previous_proto == new_proto)) return(0); switch (previous_proto) { case NDPI_PROTOCOL_WHATSAPP_CALL: case NDPI_PROTOCOL_WHATSAPP_FILES: if(new_proto == NDPI_PROTOCOL_WHATSAPP) return(1); } return(0); } /* ****************************************************** */ static u_int16_t ndpi_automa_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, u_int16_t master_protocol_id, ndpi_protocol_match_result *ret_match, u_int8_t is_host_match) { int matching_protocol_id; struct ndpi_packet_struct *packet = &flow->packet; matching_protocol_id = ndpi_match_string_subprotocol(ndpi_str, string_to_match, string_to_match_len, ret_match, is_host_match); #ifdef DEBUG { char m[256]; int len = ndpi_min(sizeof(m), string_to_match_len); strncpy(m, string_to_match, len); m[len] = '\0'; NDPI_LOG_DBG2(ndpi_str, "[NDPI] ndpi_match_host_subprotocol(%s): %s\n", m, ndpi_str->proto_defaults[matching_protocol_id].protoName); } #endif if((matching_protocol_id != NDPI_PROTOCOL_UNKNOWN) && (!ndpi_is_more_generic_protocol(packet->detected_protocol_stack[0], matching_protocol_id))) { /* Move the protocol on slot 0 down one position */ packet->detected_protocol_stack[1] = master_protocol_id, packet->detected_protocol_stack[0] = matching_protocol_id; flow->detected_protocol_stack[0] = packet->detected_protocol_stack[0], flow->detected_protocol_stack[1] = packet->detected_protocol_stack[1]; if(flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) flow->category = ret_match->protocol_category; return(packet->detected_protocol_stack[0]); } #ifdef DEBUG string_to_match[string_to_match_len] = '\0'; NDPI_LOG_DBG2(ndpi_str, "[NTOP] Unable to find a match for '%s'\n", string_to_match); #endif ret_match->protocol_id = NDPI_PROTOCOL_UNKNOWN, ret_match->protocol_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, ret_match->protocol_breed = NDPI_PROTOCOL_UNRATED; return(NDPI_PROTOCOL_UNKNOWN); } /* ****************************************************** */ u_int16_t ndpi_match_host_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int16_t master_protocol_id) { u_int16_t rc = ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len, master_protocol_id, ret_match, 1); ndpi_protocol_category_t id = ret_match->protocol_category; if(ndpi_get_custom_category_match(ndpi_str, string_to_match, string_to_match_len, &id) != -1) { /* if(id != -1) */ { flow->category = ret_match->protocol_category = id; rc = master_protocol_id; } } return(rc); } /* **************************************** */ int ndpi_match_hostname_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t master_protocol, char *name, u_int name_len) { ndpi_protocol_match_result ret_match; u_int16_t subproto, what_len; char *what; if((name_len > 2) && (name[0] == '*') && (name[1] == '.')) what = &name[1], what_len = name_len - 1; else what = name, what_len = name_len; subproto = ndpi_match_host_subprotocol(ndpi_struct, flow, what, what_len, &ret_match, master_protocol); if(subproto != NDPI_PROTOCOL_UNKNOWN) { ndpi_set_detected_protocol(ndpi_struct, flow, subproto, master_protocol); ndpi_int_change_category(ndpi_struct, flow, ret_match.protocol_category); return(1); } else return(0); } /* ****************************************************** */ u_int16_t ndpi_match_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *string_to_match, u_int string_to_match_len, ndpi_protocol_match_result *ret_match, u_int16_t master_protocol_id) { return(ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len, master_protocol_id, ret_match, 0)); } /* ****************************************************** */ int ndpi_match_bigram(struct ndpi_detection_module_struct *ndpi_str, ndpi_automa *automa, char *bigram_to_match) { AC_TEXT_t ac_input_text; AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED}; int rc; if((automa->ac_automa == NULL) || (bigram_to_match == NULL)) return(-1); if(!automa->ac_automa_finalized) { #if 1 ndpi_finalize_initalization(ndpi_str); #else printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__); return(0); /* No matches */ #endif } ac_input_text.astring = bigram_to_match, ac_input_text.length = 2; rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match); /* As ac_automata_search can detect partial matches and continue the search process in case rc == 0 (i.e. no match), we need to check if there is a partial match and in this case return it */ if((rc == 0) && (match.number != 0)) rc = 1; return(rc ? match.number : 0); } /* ****************************************************** */ void ndpi_free_flow(struct ndpi_flow_struct *flow) { if(flow) { if(flow->http.url) ndpi_free(flow->http.url); if(flow->http.content_type) ndpi_free(flow->http.content_type); if(flow->http.user_agent) ndpi_free(flow->http.user_agent); if(flow->kerberos_buf.pktbuf) ndpi_free(flow->kerberos_buf.pktbuf); if(flow_is_proto(flow, NDPI_PROTOCOL_TLS)) { if(flow->protos.stun_ssl.ssl.server_names) ndpi_free(flow->protos.stun_ssl.ssl.server_names); if(flow->protos.stun_ssl.ssl.alpn) ndpi_free(flow->protos.stun_ssl.ssl.alpn); if(flow->protos.stun_ssl.ssl.tls_supported_versions) ndpi_free(flow->protos.stun_ssl.ssl.tls_supported_versions); if(flow->protos.stun_ssl.ssl.issuerDN) ndpi_free(flow->protos.stun_ssl.ssl.issuerDN); if(flow->protos.stun_ssl.ssl.subjectDN) ndpi_free(flow->protos.stun_ssl.ssl.subjectDN); if(flow->l4.tcp.tls.srv_cert_fingerprint_ctx) ndpi_free(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) ndpi_free(flow->protos.stun_ssl.ssl.encrypted_sni.esni); } if(flow->l4_proto == IPPROTO_TCP) { if(flow->l4.tcp.tls.message.buffer) ndpi_free(flow->l4.tcp.tls.message.buffer); } ndpi_free(flow); } } /* ****************************************************** */ char *ndpi_revision() { return(NDPI_GIT_RELEASE); } /* ****************************************************** */ #ifdef WIN32 /* https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows */ int gettimeofday(struct timeval *tp, struct timezone *tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) // until 00:00:00 January 1, 1970 static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t) file_time.dwLowDateTime); time += ((uint64_t) file_time.dwHighDateTime) << 32; tp->tv_sec = (long) ((time - EPOCH) / 10000000L); tp->tv_usec = (long) (system_time.wMilliseconds * 1000); return(0); } #endif int NDPI_BITMASK_COMPARE(NDPI_PROTOCOL_BITMASK a, NDPI_PROTOCOL_BITMASK b) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) { if(a.fds_bits[i] & b.fds_bits[i]) return(1); } return(0); } #ifdef CODE_UNUSED int NDPI_BITMASK_IS_EMPTY(NDPI_PROTOCOL_BITMASK a) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) if(a.fds_bits[i] != 0) return(0); return(1); } void NDPI_DUMP_BITMASK(NDPI_PROTOCOL_BITMASK a) { int i; for (i = 0; i < NDPI_NUM_FDS_BITS; i++) printf("[%d=%u]", i, a.fds_bits[i]); printf("\n"); } #endif u_int16_t ndpi_get_api_version() { return(NDPI_API_VERSION); } ndpi_proto_defaults_t *ndpi_get_proto_defaults(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->proto_defaults); } u_int ndpi_get_ndpi_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_supported_protocols); } u_int ndpi_get_ndpi_num_custom_protocols(struct ndpi_detection_module_struct *ndpi_str) { return(ndpi_str->ndpi_num_custom_protocols); } u_int ndpi_get_ndpi_detection_module_size() { return(sizeof(struct ndpi_detection_module_struct)); } void ndpi_set_log_level(struct ndpi_detection_module_struct *ndpi_str, u_int l){ ndpi_str->ndpi_log_level = l; } /* ******************************************************************** */ /* LRU cache */ struct ndpi_lru_cache *ndpi_lru_cache_init(u_int32_t num_entries) { struct ndpi_lru_cache *c = (struct ndpi_lru_cache *) ndpi_malloc(sizeof(struct ndpi_lru_cache)); if(!c) return(NULL); c->entries = (struct ndpi_lru_cache_entry *) ndpi_calloc(num_entries, sizeof(struct ndpi_lru_cache_entry)); if(!c->entries) { ndpi_free(c); return(NULL); } else c->num_entries = num_entries; return(c); } void ndpi_lru_free_cache(struct ndpi_lru_cache *c) { ndpi_free(c->entries); ndpi_free(c); } u_int8_t ndpi_lru_find_cache(struct ndpi_lru_cache *c, u_int32_t key, u_int16_t *value, u_int8_t clean_key_when_found) { u_int32_t slot = key % c->num_entries; if(c->entries[slot].is_full) { *value = c->entries[slot].value; if(clean_key_when_found) c->entries[slot].is_full = 0; return(1); } else return(0); } void ndpi_lru_add_to_cache(struct ndpi_lru_cache *c, u_int32_t key, u_int16_t value) { u_int32_t slot = key % c->num_entries; c->entries[slot].is_full = 1, c->entries[slot].key = key, c->entries[slot].value = value; } /* ******************************************************************** */ /* This function tells if it's possible to further dissect a given flow 0 - All possible dissection has been completed 1 - Additional dissection is possible */ u_int8_t ndpi_extra_dissection_possible(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) { u_int16_t proto = flow->detected_protocol_stack[1] ? flow->detected_protocol_stack[1] : flow->detected_protocol_stack[0]; #if 0 printf("[DEBUG] %s(%u.%u): %u\n", __FUNCTION__, flow->detected_protocol_stack[0], flow->detected_protocol_stack[1], proto); #endif switch (proto) { case NDPI_PROTOCOL_TLS: if(!flow->l4.tcp.tls.certificate_processed) return(1); /* TODO: add check for TLS 1.3 */ break; case NDPI_PROTOCOL_HTTP: if((flow->host_server_name[0] == '\0') || (flow->http.response_status_code == 0)) return(1); break; case NDPI_PROTOCOL_DNS: if(flow->protos.dns.num_answers == 0) return(1); break; case NDPI_PROTOCOL_FTP_CONTROL: case NDPI_PROTOCOL_MAIL_POP: case NDPI_PROTOCOL_MAIL_IMAP: case NDPI_PROTOCOL_MAIL_SMTP: if(flow->protos.ftp_imap_pop_smtp.password[0] == '\0') return(1); break; case NDPI_PROTOCOL_SSH: if((flow->protos.ssh.hassh_client[0] == '\0') || (flow->protos.ssh.hassh_server[0] == '\0')) return(1); break; case NDPI_PROTOCOL_TELNET: if(!flow->protos.telnet.password_detected) return(1); break; } return(0); } /* ******************************************************************** */ const char *ndpi_get_l4_proto_name(ndpi_l4_proto_info proto) { switch (proto) { case ndpi_l4_proto_unknown: return(""); break; case ndpi_l4_proto_tcp_only: return("TCP"); break; case ndpi_l4_proto_udp_only: return("UDP"); break; case ndpi_l4_proto_tcp_and_udp: return("TCP/UDP"); break; } return(""); } /* ******************************************************************** */ ndpi_l4_proto_info ndpi_get_l4_proto_info(struct ndpi_detection_module_struct *ndpi_struct, u_int16_t ndpi_proto_id) { if(ndpi_proto_id < ndpi_struct->ndpi_num_supported_protocols) { u_int16_t idx = ndpi_struct->proto_defaults[ndpi_proto_id].protoIdx; NDPI_SELECTION_BITMASK_PROTOCOL_SIZE bm = ndpi_struct->callback_buffer[idx].ndpi_selection_bitmask; if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP) return(ndpi_l4_proto_tcp_only); else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP) return(ndpi_l4_proto_udp_only); else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP) return(ndpi_l4_proto_tcp_and_udp); } return(ndpi_l4_proto_unknown); /* default */ } /* ******************************************************************** */ ndpi_ptree_t *ndpi_ptree_create(void) { ndpi_ptree_t *tree = (ndpi_ptree_t *) ndpi_malloc(sizeof(ndpi_ptree_t)); if(tree) { tree->v4 = ndpi_New_Patricia(32); tree->v6 = ndpi_New_Patricia(128); if((!tree->v4) || (!tree->v6)) { ndpi_ptree_destroy(tree); return(NULL); } } return(tree); } /* ******************************************************************** */ void ndpi_ptree_destroy(ndpi_ptree_t *tree) { if(tree) { if(tree->v4) ndpi_Destroy_Patricia(tree->v4, free_ptree_data); if(tree->v6) ndpi_Destroy_Patricia(tree->v6, free_ptree_data); ndpi_free(tree); } } /* ******************************************************************** */ int ndpi_ptree_insert(ndpi_ptree_t *tree, const ndpi_ip_addr_t *addr, u_int8_t bits, uint user_data) { u_int8_t is_v6 = ndpi_is_ipv6(addr); patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4; prefix_t prefix; patricia_node_t *node; if(bits > ptree->maxbits) return(-1); if(is_v6) fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits); else fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits); /* Verify that the node does not already exist */ node = ndpi_patricia_search_best(ptree, &prefix); if(node && (node->prefix->bitlen == bits)) return(-2); node = ndpi_patricia_lookup(ptree, &prefix); if(node != NULL) { node->value.uv.user_value = user_data, node->value.uv.additional_user_value = 0; return(0); } return(-3); } /* ******************************************************************** */ int ndpi_ptree_match_addr(ndpi_ptree_t *tree, const ndpi_ip_addr_t *addr, uint *user_data) { u_int8_t is_v6 = ndpi_is_ipv6(addr); patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4; prefix_t prefix; patricia_node_t *node; int bits = ptree->maxbits; if(is_v6) fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits); else fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits); node = ndpi_patricia_search_best(ptree, &prefix); if(node) { *user_data = node->value.uv.user_value; return(0); } return(-1); } /* ******************************************************************** */ void ndpi_md5(const u_char *data, size_t data_len, u_char hash[16]) { ndpi_MD5_CTX ctx; ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, data, data_len); ndpi_MD5Final(hash, &ctx); } /* ******************************************************************** */ static int enough(int a, int b) { u_int8_t percentage = 20; if(b == 0) return(0); if(a == 0) return(1); if(b > (((a+1)*percentage)/100)) return(1); return(0); } /* ******************************************************************** */ // #define DGA_DEBUG 1 int ndpi_check_dga_name(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow, char *name) { int len, rc = 0; len = strlen(name); if(len >= 5) { int i, j, num_found = 0, num_impossible = 0, num_bigram_checks = 0, num_digits = 0, num_vowels = 0, num_words = 0; char tmp[128], *word, *tok_tmp; len = snprintf(tmp, sizeof(tmp)-1, "%s", name); if(len < 0) return(0); for(i=0, j=0; (i<len) && (j<(sizeof(tmp)-1)); i++) { tmp[j++] = tolower(name[i]); } tmp[j] = '\0'; len = j; for(word = strtok_r(tmp, ".", &tok_tmp); ; word = strtok_r(NULL, ".", &tok_tmp)) { if(!word) break; num_words++; if(strlen(word) < 3) continue; #ifdef DGA_DEBUG printf("-> %s [%s][len: %u]\n", word, name, (unsigned int)strlen(word)); #endif for(i = 0; word[i+1] != '\0'; i++) { if(isdigit(word[i])) { num_digits++; // if(!isdigit(word[i+1])) num_impossible++; continue; } switch(word[i]) { case '_': case '-': case ':': continue; break; case '.': continue; break; } switch(word[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': num_vowels++; break; } if(isdigit(word[i+1])) { num_digits++; // num_impossible++; continue; } num_bigram_checks++; if(ndpi_match_bigram(ndpi_str, &ndpi_str->bigrams_automa, &word[i])) { num_found++; } else { if(ndpi_match_bigram(ndpi_str, &ndpi_str->impossible_bigrams_automa, &word[i])) { #ifdef DGA_DEBUG printf("IMPOSSIBLE %s\n", &word[i]); #endif num_impossible++; } } } /* for */ } /* for */ #ifdef DGA_DEBUG printf("[num_found: %u][num_impossible: %u][num_digits: %u][num_bigram_checks: %u][num_vowels: %u/%u]\n", num_found, num_impossible, num_digits, num_bigram_checks, num_vowels, j-num_vowels); #endif if(num_bigram_checks && ((num_found == 0) || ((num_digits > 5) && (num_words <= 3)) || enough(num_found, num_impossible))) rc = 1; if(rc && flow) NDPI_SET_BIT(flow->risk, NDPI_SUSPICIOUS_DGA_DOMAIN); #ifdef DGA_DEBUG if(rc) printf("DGA %s [num_found: %u][num_impossible: %u]\n", name, num_found, num_impossible); #endif } return(rc); }
static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; }
static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL, packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; }
{'added': [(4339, ' packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,'), (4340, ' packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,')], 'deleted': [(4339, ' packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,')]}
2
1
4,575
40,634
https://github.com/ntop/nDPI
CVE-2020-15475
['CWE-416']
arp_tables.c
check_entry_size_and_hooks
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
{'added': [(362, 'static inline bool unconditional(const struct arpt_entry *e)'), (366, '\treturn e->target_offset == sizeof(struct arpt_entry) &&'), (367, '\t memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;'), (406, '\t\t\tif ((unconditional(e) &&'), (409, '\t\t\t t->verdict < 0) || visited) {'), (554, '\tif (!unconditional(e))'), (601, '\t\t\t\tpr_debug("Underflows must be unconditional and "'), (602, '\t\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t\t "ACCEPT/DROP\\n");')], 'deleted': [(362, 'static inline bool unconditional(const struct arpt_arp *arp)'), (366, '\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;'), (405, '\t\t\tif ((e->target_offset == sizeof(struct arpt_entry) &&'), (408, '\t\t\t t->verdict < 0 && unconditional(&e->arp)) ||'), (409, '\t\t\t visited) {'), (554, '\tif (!unconditional(&e->arp))'), (601, '\t\t\t\tpr_err("Underflows must be unconditional and "'), (602, '\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t "ACCEPT/DROP\\n");')]}
9
9
1,537
9,605
https://github.com/torvalds/linux
CVE-2016-3134
['CWE-119']
arp_tables.c
check_underflow
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; }
static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; }
{'added': [(362, 'static inline bool unconditional(const struct arpt_entry *e)'), (366, '\treturn e->target_offset == sizeof(struct arpt_entry) &&'), (367, '\t memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;'), (406, '\t\t\tif ((unconditional(e) &&'), (409, '\t\t\t t->verdict < 0) || visited) {'), (554, '\tif (!unconditional(e))'), (601, '\t\t\t\tpr_debug("Underflows must be unconditional and "'), (602, '\t\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t\t "ACCEPT/DROP\\n");')], 'deleted': [(362, 'static inline bool unconditional(const struct arpt_arp *arp)'), (366, '\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;'), (405, '\t\t\tif ((e->target_offset == sizeof(struct arpt_entry) &&'), (408, '\t\t\t t->verdict < 0 && unconditional(&e->arp)) ||'), (409, '\t\t\t visited) {'), (554, '\tif (!unconditional(&e->arp))'), (601, '\t\t\t\tpr_err("Underflows must be unconditional and "'), (602, '\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t "ACCEPT/DROP\\n");')]}
9
9
1,537
9,605
https://github.com/torvalds/linux
CVE-2016-3134
['CWE-119']
arp_tables.c
mark_source_chains
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; }
static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; }
{'added': [(362, 'static inline bool unconditional(const struct arpt_entry *e)'), (366, '\treturn e->target_offset == sizeof(struct arpt_entry) &&'), (367, '\t memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;'), (406, '\t\t\tif ((unconditional(e) &&'), (409, '\t\t\t t->verdict < 0) || visited) {'), (554, '\tif (!unconditional(e))'), (601, '\t\t\t\tpr_debug("Underflows must be unconditional and "'), (602, '\t\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t\t "ACCEPT/DROP\\n");')], 'deleted': [(362, 'static inline bool unconditional(const struct arpt_arp *arp)'), (366, '\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;'), (405, '\t\t\tif ((e->target_offset == sizeof(struct arpt_entry) &&'), (408, '\t\t\t t->verdict < 0 && unconditional(&e->arp)) ||'), (409, '\t\t\t visited) {'), (554, '\tif (!unconditional(&e->arp))'), (601, '\t\t\t\tpr_err("Underflows must be unconditional and "'), (602, '\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t "ACCEPT/DROP\\n");')]}
9
9
1,537
9,605
https://github.com/torvalds/linux
CVE-2016-3134
['CWE-119']
arp_tables.c
unconditional
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
/* * Packet matching code for ARP packets. * * Based heavily, if not almost entirely, upon ip_tables.c framework. * * Some ARP specific bits are: * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net> * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/capability.h> #include <linux/if_arp.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/err.h> #include <net/compat.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_arp/arp_tables.h> #include "../../netfilter/xt_repldata.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("David S. Miller <davem@redhat.com>"); MODULE_DESCRIPTION("arptables core"); /*#define DEBUG_ARP_TABLES*/ /*#define DEBUG_ARP_TABLES_USER*/ #ifdef DEBUG_ARP_TABLES #define dprintf(format, args...) pr_debug(format, ## args) #else #define dprintf(format, args...) #endif #ifdef DEBUG_ARP_TABLES_USER #define duprintf(format, args...) pr_debug(format, ## args) #else #define duprintf(format, args...) #endif #ifdef CONFIG_NETFILTER_DEBUG #define ARP_NF_ASSERT(x) WARN_ON(!(x)) #else #define ARP_NF_ASSERT(x) #endif void *arpt_alloc_initial_table(const struct xt_table *info) { return xt_alloc_initial_table(arpt, ARPT); } EXPORT_SYMBOL_GPL(arpt_alloc_initial_table); static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap, const char *hdr_addr, int len) { int i, ret; if (len > ARPT_DEV_ADDR_LEN_MAX) len = ARPT_DEV_ADDR_LEN_MAX; ret = 0; for (i = 0; i < len; i++) ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i]; return ret != 0; } /* * Unfortunately, _b and _mask are not aligned to an int (or long int) * Some arches dont care, unrolling the loop is a win on them. * For other arches, we only have a 16bit alignement. */ static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask) { #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS unsigned long ret = ifname_compare_aligned(_a, _b, _mask); #else unsigned long ret = 0; const u16 *a = (const u16 *)_a; const u16 *b = (const u16 *)_b; const u16 *mask = (const u16 *)_mask; int i; for (i = 0; i < IFNAMSIZ/sizeof(u16); i++) ret |= (a[i] ^ b[i]) & mask[i]; #endif return ret; } /* Returns whether packet matches rule or not. */ static inline int arp_packet_match(const struct arphdr *arphdr, struct net_device *dev, const char *indev, const char *outdev, const struct arpt_arp *arpinfo) { const char *arpptr = (char *)(arphdr + 1); const char *src_devaddr, *tgt_devaddr; __be32 src_ipaddr, tgt_ipaddr; long ret; #define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg))) if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop, ARPT_INV_ARPOP)) { dprintf("ARP operation field mismatch.\n"); dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n", arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask); return 0; } if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd, ARPT_INV_ARPHRD)) { dprintf("ARP hardware address format mismatch.\n"); dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n", arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask); return 0; } if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro, ARPT_INV_ARPPRO)) { dprintf("ARP protocol address format mismatch.\n"); dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n", arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask); return 0; } if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln, ARPT_INV_ARPHLN)) { dprintf("ARP hardware address length mismatch.\n"); dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n", arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask); return 0; } src_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&src_ipaddr, arpptr, sizeof(u32)); arpptr += sizeof(u32); tgt_devaddr = arpptr; arpptr += dev->addr_len; memcpy(&tgt_ipaddr, arpptr, sizeof(u32)); if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len), ARPT_INV_SRCDEVADDR) || FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len), ARPT_INV_TGTDEVADDR)) { dprintf("Source or target device address mismatch.\n"); return 0; } if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr, ARPT_INV_SRCIP) || FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr), ARPT_INV_TGTIP)) { dprintf("Source or target IP address mismatch.\n"); dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n", &src_ipaddr, &arpinfo->smsk.s_addr, &arpinfo->src.s_addr, arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : ""); dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n", &tgt_ipaddr, &arpinfo->tmsk.s_addr, &arpinfo->tgt.s_addr, arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : ""); return 0; } /* Look for ifname matches. */ ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_IN)) { dprintf("VIA in mismatch (%s vs %s).%s\n", indev, arpinfo->iniface, arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : ""); return 0; } ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask); if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) { dprintf("VIA out mismatch (%s vs %s).%s\n", outdev, arpinfo->outiface, arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : ""); return 0; } return 1; #undef FWINV } static inline int arp_checkentry(const struct arpt_arp *arp) { if (arp->flags & ~ARPT_F_MASK) { duprintf("Unknown flag bits set: %08X\n", arp->flags & ~ARPT_F_MASK); return 0; } if (arp->invflags & ~ARPT_INV_MASK) { duprintf("Unknown invflag bits set: %08X\n", arp->invflags & ~ARPT_INV_MASK); return 0; } return 1; } static unsigned int arpt_error(struct sk_buff *skb, const struct xt_action_param *par) { net_err_ratelimited("arp_tables: error: '%s'\n", (const char *)par->targinfo); return NF_DROP; } static inline const struct xt_entry_target * arpt_get_target_c(const struct arpt_entry *e) { return arpt_get_target((struct arpt_entry *)e); } static inline struct arpt_entry * get_entry(const void *base, unsigned int offset) { return (struct arpt_entry *)(base + offset); } static inline struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry) { return (void *)entry + entry->next_offset; } unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = table->private; cpu = smp_processor_id(); /* * Ensure we load private-> members after we've fetched the base * pointer. */ smp_read_barrier_depends(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.net = state->net; acpar.in = state->in; acpar.out = state->out; acpar.hooknum = hook; acpar.family = NFPROTO_ARP; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); /* Target might have changed stuff. */ arp = arp_hdr(skb); if (verdict == XT_CONTINUE) e = arpt_next_entry(e); else /* Verdict */ break; } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } /* All zeroes == unconditional rule. */ static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; } /* Figures out from what hook each rule can be called: returns 0 if * there are loops. Puts hook bitmask in comefrom. */ static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } static inline int check_entry(const struct arpt_entry *e) { const struct xt_entry_target *t; if (!arp_checkentry(&e->arp)) return -EINVAL; if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset) return -EINVAL; t = arpt_get_target_c(e); if (e->target_offset + t->u.target_size > e->next_offset) return -EINVAL; return 0; } static inline int check_target(struct arpt_entry *e, const char *name) { struct xt_entry_target *t = arpt_get_target(e); int ret; struct xt_tgchk_param par = { .table = name, .entryinfo = e, .target = t->u.kernel.target, .targinfo = t->data, .hook_mask = e->comefrom, .family = NFPROTO_ARP, }; ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false); if (ret < 0) { duprintf("arp_tables: check failed for `%s'.\n", t->u.kernel.target->name); return ret; } return 0; } static inline int find_check_entry(struct arpt_entry *e, const char *name, unsigned int size) { struct xt_entry_target *t; struct xt_target *target; int ret; e->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(e->counters.pcnt)) return -ENOMEM; t = arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("find_check_entry: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; ret = check_target(e, name); if (ret) goto err; return 0; err: module_put(t->u.kernel.target->me); out: xt_percpu_counter_free(e->counters.pcnt); return ret; } static bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(e)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } static inline void cleanup_entry(struct arpt_entry *e) { struct xt_tgdtor_param par; struct xt_entry_target *t; t = arpt_get_target(e); par.target = t->u.kernel.target; par.targinfo = t->data; par.family = NFPROTO_ARP; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); xt_percpu_counter_free(e->counters.pcnt); } /* Checks and translates the user-supplied table segment (held in * newinfo). */ static int translate_table(struct xt_table_info *newinfo, void *entry0, const struct arpt_replace *repl) { struct arpt_entry *iter; unsigned int i; int ret = 0; newinfo->size = repl->size; newinfo->number = repl->num_entries; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = 0xFFFFFFFF; newinfo->underflow[i] = 0xFFFFFFFF; } duprintf("translate_table: size %u\n", newinfo->size); i = 0; /* Walk through entries, checking offsets. */ xt_entry_foreach(iter, entry0, newinfo->size) { ret = check_entry_size_and_hooks(iter, newinfo, entry0, entry0 + repl->size, repl->hook_entry, repl->underflow, repl->valid_hooks); if (ret != 0) break; ++i; if (strcmp(arpt_get_target(iter)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret); if (ret != 0) return ret; if (i != repl->num_entries) { duprintf("translate_table: %u not %u entries\n", i, repl->num_entries); return -EINVAL; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(repl->valid_hooks & (1 << i))) continue; if (newinfo->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, repl->hook_entry[i]); return -EINVAL; } if (newinfo->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, repl->underflow[i]); return -EINVAL; } } if (!mark_source_chains(newinfo, repl->valid_hooks, entry0)) { duprintf("Looping hook\n"); return -ELOOP; } /* Finally, each sanity check must pass */ i = 0; xt_entry_foreach(iter, entry0, newinfo->size) { ret = find_check_entry(iter, repl->name, repl->size); if (ret != 0) break; ++i; } if (ret != 0) { xt_entry_foreach(iter, entry0, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter); } return ret; } return ret; } static void get_counters(const struct xt_table_info *t, struct xt_counters counters[]) { struct arpt_entry *iter; unsigned int cpu; unsigned int i; for_each_possible_cpu(cpu) { seqcount_t *s = &per_cpu(xt_recseq, cpu); i = 0; xt_entry_foreach(iter, t->entries, t->size) { struct xt_counters *tmp; u64 bcnt, pcnt; unsigned int start; tmp = xt_get_per_cpu_counter(&iter->counters, cpu); do { start = read_seqcount_begin(s); bcnt = tmp->bcnt; pcnt = tmp->pcnt; } while (read_seqcount_retry(s, start)); ADD_COUNTER(counters[i], bcnt, pcnt); ++i; } } } static struct xt_counters *alloc_counters(const struct xt_table *table) { unsigned int countersize; struct xt_counters *counters; const struct xt_table_info *private = table->private; /* We need atomic snapshot of counters: rest doesn't change * (other than comefrom, which userspace doesn't care * about). */ countersize = sizeof(struct xt_counters) * private->number; counters = vzalloc(countersize); if (counters == NULL) return ERR_PTR(-ENOMEM); get_counters(private, counters); return counters; } static int copy_entries_to_user(unsigned int total_size, const struct xt_table *table, void __user *userptr) { unsigned int off, num; const struct arpt_entry *e; struct xt_counters *counters; struct xt_table_info *private = table->private; int ret = 0; void *loc_cpu_entry; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); loc_cpu_entry = private->entries; /* ... then copy entire thing ... */ if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) { ret = -EFAULT; goto free_counters; } /* FIXME: use iterator macros --RR */ /* ... then go back and fix counters and names */ for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){ const struct xt_entry_target *t; e = (struct arpt_entry *)(loc_cpu_entry + off); if (copy_to_user(userptr + off + offsetof(struct arpt_entry, counters), &counters[num], sizeof(counters[num])) != 0) { ret = -EFAULT; goto free_counters; } t = arpt_get_target_c(e); if (copy_to_user(userptr + off + e->target_offset + offsetof(struct xt_entry_target, u.user.name), t->u.kernel.target->name, strlen(t->u.kernel.target->name)+1) != 0) { ret = -EFAULT; goto free_counters; } } free_counters: vfree(counters); return ret; } #ifdef CONFIG_COMPAT static void compat_standard_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v > 0) v += xt_compat_calc_jump(NFPROTO_ARP, v); memcpy(dst, &v, sizeof(v)); } static int compat_standard_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv > 0) cv -= xt_compat_calc_jump(NFPROTO_ARP, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } static int compat_calc_entry(const struct arpt_entry *e, const struct xt_table_info *info, const void *base, struct xt_table_info *newinfo) { const struct xt_entry_target *t; unsigned int entry_offset; int off, i, ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - base; t = arpt_get_target_c(e); off += xt_compat_target_offset(t->u.kernel.target); newinfo->size -= off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { if (info->hook_entry[i] && (e < (struct arpt_entry *)(base + info->hook_entry[i]))) newinfo->hook_entry[i] -= off; if (info->underflow[i] && (e < (struct arpt_entry *)(base + info->underflow[i]))) newinfo->underflow[i] -= off; } return 0; } static int compat_table_info(const struct xt_table_info *info, struct xt_table_info *newinfo) { struct arpt_entry *iter; const void *loc_cpu_entry; int ret; if (!newinfo || !info) return -EINVAL; /* we dont care about newinfo->entries */ memcpy(newinfo, info, offsetof(struct xt_table_info, entries)); newinfo->initial_entries = 0; loc_cpu_entry = info->entries; xt_compat_init_offsets(NFPROTO_ARP, info->number); xt_entry_foreach(iter, loc_cpu_entry, info->size) { ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo); if (ret != 0) return ret; } return 0; } #endif static int get_info(struct net *net, void __user *user, const int *len, int compat) { char name[XT_TABLE_MAXNAMELEN]; struct xt_table *t; int ret; if (*len != sizeof(struct arpt_getinfo)) { duprintf("length %u != %Zu\n", *len, sizeof(struct arpt_getinfo)); return -EINVAL; } if (copy_from_user(name, user, sizeof(name)) != 0) return -EFAULT; name[XT_TABLE_MAXNAMELEN-1] = '\0'; #ifdef CONFIG_COMPAT if (compat) xt_compat_lock(NFPROTO_ARP); #endif t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (!IS_ERR_OR_NULL(t)) { struct arpt_getinfo info; const struct xt_table_info *private = t->private; #ifdef CONFIG_COMPAT struct xt_table_info tmp; if (compat) { ret = compat_table_info(private, &tmp); xt_compat_flush_offsets(NFPROTO_ARP); private = &tmp; } #endif memset(&info, 0, sizeof(info)); info.valid_hooks = t->valid_hooks; memcpy(info.hook_entry, private->hook_entry, sizeof(info.hook_entry)); memcpy(info.underflow, private->underflow, sizeof(info.underflow)); info.num_entries = private->number; info.size = private->size; strcpy(info.name, name); if (copy_to_user(user, &info, *len) != 0) ret = -EFAULT; else ret = 0; xt_table_unlock(t); module_put(t->me); } else ret = t ? PTR_ERR(t) : -ENOENT; #ifdef CONFIG_COMPAT if (compat) xt_compat_unlock(NFPROTO_ARP); #endif return ret; } static int get_entries(struct net *net, struct arpt_get_entries __user *uptr, const int *len) { int ret; struct arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("get_entries: %u < %Zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct arpt_get_entries) + get.size) { duprintf("get_entries: %u != %Zu\n", *len, sizeof(struct arpt_get_entries) + get.size); return -EINVAL; } t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; duprintf("t->private->number = %u\n", private->number); if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else { duprintf("get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; return ret; } static int __do_replace(struct net *net, const char *name, unsigned int valid_hooks, struct xt_table_info *newinfo, unsigned int num_counters, void __user *counters_ptr) { int ret; struct xt_table *t; struct xt_table_info *oldinfo; struct xt_counters *counters; void *loc_cpu_old_entry; struct arpt_entry *iter; ret = 0; counters = vzalloc(num_counters * sizeof(struct xt_counters)); if (!counters) { ret = -ENOMEM; goto out; } t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name), "arptable_%s", name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free_newinfo_counters_untrans; } /* You lied! */ if (valid_hooks != t->valid_hooks) { duprintf("Valid hook crap: %08X vs %08X\n", valid_hooks, t->valid_hooks); ret = -EINVAL; goto put_module; } oldinfo = xt_replace_table(t, num_counters, newinfo, &ret); if (!oldinfo) goto put_module; /* Update module usage count based on number of rules */ duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n", oldinfo->number, oldinfo->initial_entries, newinfo->number); if ((oldinfo->number > oldinfo->initial_entries) || (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); if ((oldinfo->number > oldinfo->initial_entries) && (newinfo->number <= oldinfo->initial_entries)) module_put(t->me); /* Get the old counters, and synchronize with replace */ get_counters(oldinfo, counters); /* Decrease module usage counts and free resource */ loc_cpu_old_entry = oldinfo->entries; xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size) cleanup_entry(iter); xt_free_table_info(oldinfo); if (copy_to_user(counters_ptr, counters, sizeof(struct xt_counters) * num_counters) != 0) { /* Silent error, can't fail, new table is already in place */ net_warn_ratelimited("arptables: counters copy to user failed while replacing table\n"); } vfree(counters); xt_table_unlock(t); return ret; put_module: module_put(t->me); xt_table_unlock(t); free_newinfo_counters_untrans: vfree(counters); out: return ret; } static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int do_add_counters(struct net *net, const void __user *user, unsigned int len, int compat) { unsigned int i; struct xt_counters_info tmp; struct xt_counters *paddc; unsigned int num_counters; const char *name; int size; void *ptmp; struct xt_table *t; const struct xt_table_info *private; int ret = 0; struct arpt_entry *iter; unsigned int addend; #ifdef CONFIG_COMPAT struct compat_xt_counters_info compat_tmp; if (compat) { ptmp = &compat_tmp; size = sizeof(struct compat_xt_counters_info); } else #endif { ptmp = &tmp; size = sizeof(struct xt_counters_info); } if (copy_from_user(ptmp, user, size) != 0) return -EFAULT; #ifdef CONFIG_COMPAT if (compat) { num_counters = compat_tmp.num_counters; name = compat_tmp.name; } else #endif { num_counters = tmp.num_counters; name = tmp.name; } if (len != size + num_counters * sizeof(struct xt_counters)) return -EINVAL; paddc = vmalloc(len - size); if (!paddc) return -ENOMEM; if (copy_from_user(paddc, user + size, len - size) != 0) { ret = -EFAULT; goto free; } t = xt_find_table_lock(net, NFPROTO_ARP, name); if (IS_ERR_OR_NULL(t)) { ret = t ? PTR_ERR(t) : -ENOENT; goto free; } local_bh_disable(); private = t->private; if (private->number != num_counters) { ret = -EINVAL; goto unlock_up_free; } i = 0; addend = xt_write_recseq_begin(); xt_entry_foreach(iter, private->entries, private->size) { struct xt_counters *tmp; tmp = xt_get_this_cpu_counter(&iter->counters); ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt); ++i; } xt_write_recseq_end(addend); unlock_up_free: local_bh_enable(); xt_table_unlock(t); module_put(t->me); free: vfree(paddc); return ret; } #ifdef CONFIG_COMPAT static inline void compat_release_entry(struct compat_arpt_entry *e) { struct xt_entry_target *t; t = compat_arpt_get_target(e); module_put(t->u.kernel.target->me); } static inline int check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct arpt_entry *)e); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; } static int compat_copy_entry_from_user(struct compat_arpt_entry *e, void **dstptr, unsigned int *size, const char *name, struct xt_table_info *newinfo, unsigned char *base) { struct xt_entry_target *t; struct xt_target *target; struct arpt_entry *de; unsigned int origsize; int ret, h; ret = 0; origsize = *size; de = (struct arpt_entry *)*dstptr; memcpy(de, e, sizeof(struct arpt_entry)); memcpy(&de->counters, &e->counters, sizeof(e->counters)); *dstptr += sizeof(struct arpt_entry); *size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); de->target_offset = e->target_offset - (origsize - *size); t = compat_arpt_get_target(e); target = t->u.kernel.target; xt_compat_target_from_user(t, dstptr, size); de->next_offset = e->next_offset - (origsize - *size); for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)de - base < newinfo->hook_entry[h]) newinfo->hook_entry[h] -= origsize - *size; if ((unsigned char *)de - base < newinfo->underflow[h]) newinfo->underflow[h] -= origsize - *size; } return ret; } static int translate_compat_table(const char *name, unsigned int valid_hooks, struct xt_table_info **pinfo, void **pentry0, unsigned int total_size, unsigned int number, unsigned int *hook_entries, unsigned int *underflows) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_entry *iter1; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = total_size; info->number = number; /* Init all hooks to impossible value. */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { info->hook_entry[i] = 0xFFFFFFFF; info->underflow[i] = 0xFFFFFFFF; } duprintf("translate_compat_table: size %u\n", info->size); j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, number); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, total_size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + total_size, hook_entries, underflows, name); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != number) { duprintf("translate_compat_table: %u not %u entries\n", j, number); goto out_unlock; } /* Check hooks all assigned */ for (i = 0; i < NF_ARP_NUMHOOKS; i++) { /* Only hooks which are valid */ if (!(valid_hooks & (1 << i))) continue; if (info->hook_entry[i] == 0xFFFFFFFF) { duprintf("Invalid hook entry %u %u\n", i, hook_entries[i]); goto out_unlock; } if (info->underflow[i] == 0xFFFFFFFF) { duprintf("Invalid underflow %u %u\n", i, underflows[i]); goto out_unlock; } } ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = number; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = info->hook_entry[i]; newinfo->underflow[i] = info->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = total_size; xt_entry_foreach(iter0, entry0, total_size) { ret = compat_copy_entry_from_user(iter0, &pos, &size, name, newinfo, entry1); if (ret != 0) break; } xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); if (ret) goto free_newinfo; ret = -ELOOP; if (!mark_source_chains(newinfo, valid_hooks, entry1)) goto free_newinfo; i = 0; xt_entry_foreach(iter1, entry1, newinfo->size) { iter1->counters.pcnt = xt_percpu_counter_alloc(); if (IS_ERR_VALUE(iter1->counters.pcnt)) { ret = -ENOMEM; break; } ret = check_target(iter1, name); if (ret != 0) { xt_percpu_counter_free(iter1->counters.pcnt); break; } ++i; if (strcmp(arpt_get_target(iter1)->u.user.name, XT_ERROR_TARGET) == 0) ++newinfo->stacksize; } if (ret) { /* * The first i matches need cleanup_entry (calls ->destroy) * because they had called ->check already. The other j-i * entries need only release. */ int skip = i; j -= i; xt_entry_foreach(iter0, entry0, newinfo->size) { if (skip-- > 0) continue; if (j-- == 0) break; compat_release_entry(iter0); } xt_entry_foreach(iter1, entry1, newinfo->size) { if (i-- == 0) break; cleanup_entry(iter1); } xt_free_table_info(newinfo); return ret; } *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); out: xt_entry_foreach(iter0, entry0, total_size) { if (j-- == 0) break; compat_release_entry(iter0); } return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); goto out; } struct compat_arpt_replace { char name[XT_TABLE_MAXNAMELEN]; u32 valid_hooks; u32 num_entries; u32 size; u32 hook_entry[NF_ARP_NUMHOOKS]; u32 underflow[NF_ARP_NUMHOOKS]; u32 num_counters; compat_uptr_t counters; struct compat_arpt_entry entries[0]; }; static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; if (tmp.num_counters == 0) return -EINVAL; tmp.name[sizeof(tmp.name)-1] = 0; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } static int compat_do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = compat_do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 1); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr, compat_uint_t *size, struct xt_counters *counters, unsigned int i) { struct xt_entry_target *t; struct compat_arpt_entry __user *ce; u_int16_t target_offset, next_offset; compat_uint_t origsize; int ret; origsize = *size; ce = (struct compat_arpt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 || copy_to_user(&ce->counters, &counters[i], sizeof(counters[i])) != 0) return -EFAULT; *dstptr += sizeof(struct compat_arpt_entry); *size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); target_offset = e->target_offset - (origsize - *size); t = arpt_get_target(e); ret = xt_compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(target_offset, &ce->target_offset) != 0 || put_user(next_offset, &ce->next_offset) != 0) return -EFAULT; return 0; } static int compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table, void __user *userptr) { struct xt_counters *counters; const struct xt_table_info *private = table->private; void __user *pos; unsigned int size; int ret = 0; unsigned int i = 0; struct arpt_entry *iter; counters = alloc_counters(table); if (IS_ERR(counters)) return PTR_ERR(counters); pos = userptr; size = total_size; xt_entry_foreach(iter, private->entries, total_size) { ret = compat_copy_entry_to_user(iter, &pos, &size, counters, i++); if (ret != 0) break; } vfree(counters); return ret; } struct compat_arpt_get_entries { char name[XT_TABLE_MAXNAMELEN]; compat_uint_t size; struct compat_arpt_entry entrytable[0]; }; static int compat_get_entries(struct net *net, struct compat_arpt_get_entries __user *uptr, int *len) { int ret; struct compat_arpt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) { duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get)); return -EINVAL; } if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct compat_arpt_get_entries) + get.size) { duprintf("compat_get_entries: %u != %zu\n", *len, sizeof(get) + get.size); return -EINVAL; } xt_compat_lock(NFPROTO_ARP); t = xt_find_table_lock(net, NFPROTO_ARP, get.name); if (!IS_ERR_OR_NULL(t)) { const struct xt_table_info *private = t->private; struct xt_table_info info; duprintf("t->private->number = %u\n", private->number); ret = compat_table_info(private, &info); if (!ret && get.size == info.size) { ret = compat_copy_entries_to_user(private->size, t, uptr->entrytable); } else if (!ret) { duprintf("compat_get_entries: I've got %u not %u!\n", private->size, get.size); ret = -EAGAIN; } xt_compat_flush_offsets(NFPROTO_ARP); module_put(t->me); xt_table_unlock(t); } else ret = t ? PTR_ERR(t) : -ENOENT; xt_compat_unlock(NFPROTO_ARP); return ret; } static int do_arpt_get_ctl(struct sock *, int, void __user *, int *); static int compat_do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 1); break; case ARPT_SO_GET_ENTRIES: ret = compat_get_entries(sock_net(sk), user, len); break; default: ret = do_arpt_get_ctl(sk, cmd, user, len); } return ret; } #endif static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case ARPT_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_arpt_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } rev.name[sizeof(rev.name)-1] = 0; try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } static void __arpt_unregister_table(struct xt_table *table) { struct xt_table_info *private; void *loc_cpu_entry; struct module *table_owner = table->me; struct arpt_entry *iter; private = xt_unregister_table(table); /* Decrease module usage counts and free resources */ loc_cpu_entry = private->entries; xt_entry_foreach(iter, loc_cpu_entry, private->size) cleanup_entry(iter); if (private->number > private->initial_entries) module_put(table_owner); xt_free_table_info(private); } int arpt_register_table(struct net *net, const struct xt_table *table, const struct arpt_replace *repl, const struct nf_hook_ops *ops, struct xt_table **res) { int ret; struct xt_table_info *newinfo; struct xt_table_info bootstrap = {0}; void *loc_cpu_entry; struct xt_table *new_table; newinfo = xt_alloc_table_info(repl->size); if (!newinfo) return -ENOMEM; loc_cpu_entry = newinfo->entries; memcpy(loc_cpu_entry, repl->entries, repl->size); ret = translate_table(newinfo, loc_cpu_entry, repl); duprintf("arpt_register_table: translate table gives %d\n", ret); if (ret != 0) goto out_free; new_table = xt_register_table(net, table, &bootstrap, newinfo); if (IS_ERR(new_table)) { ret = PTR_ERR(new_table); goto out_free; } /* set res now, will see skbs right after nf_register_net_hooks */ WRITE_ONCE(*res, new_table); ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks)); if (ret != 0) { __arpt_unregister_table(new_table); *res = NULL; } return ret; out_free: xt_free_table_info(newinfo); return ret; } void arpt_unregister_table(struct net *net, struct xt_table *table, const struct nf_hook_ops *ops) { nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks)); __arpt_unregister_table(table); } /* The built-in targets: standard (NULL) and error. */ static struct xt_target arpt_builtin_tg[] __read_mostly = { { .name = XT_STANDARD_TARGET, .targetsize = sizeof(int), .family = NFPROTO_ARP, #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = compat_standard_from_user, .compat_to_user = compat_standard_to_user, #endif }, { .name = XT_ERROR_TARGET, .target = arpt_error, .targetsize = XT_FUNCTION_MAXNAMELEN, .family = NFPROTO_ARP, }, }; static struct nf_sockopt_ops arpt_sockopts = { .pf = PF_INET, .set_optmin = ARPT_BASE_CTL, .set_optmax = ARPT_SO_SET_MAX+1, .set = do_arpt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_arpt_set_ctl, #endif .get_optmin = ARPT_BASE_CTL, .get_optmax = ARPT_SO_GET_MAX+1, .get = do_arpt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_arpt_get_ctl, #endif .owner = THIS_MODULE, }; static int __net_init arp_tables_net_init(struct net *net) { return xt_proto_init(net, NFPROTO_ARP); } static void __net_exit arp_tables_net_exit(struct net *net) { xt_proto_fini(net, NFPROTO_ARP); } static struct pernet_operations arp_tables_net_ops = { .init = arp_tables_net_init, .exit = arp_tables_net_exit, }; static int __init arp_tables_init(void) { int ret; ret = register_pernet_subsys(&arp_tables_net_ops); if (ret < 0) goto err1; /* No one else will be downing sem now, so we won't sleep */ ret = xt_register_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); if (ret < 0) goto err2; /* Register setsockopt */ ret = nf_register_sockopt(&arpt_sockopts); if (ret < 0) goto err4; pr_info("arp_tables: (C) 2002 David S. Miller\n"); return 0; err4: xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); err2: unregister_pernet_subsys(&arp_tables_net_ops); err1: return ret; } static void __exit arp_tables_fini(void) { nf_unregister_sockopt(&arpt_sockopts); xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg)); unregister_pernet_subsys(&arp_tables_net_ops); } EXPORT_SYMBOL(arpt_register_table); EXPORT_SYMBOL(arpt_unregister_table); EXPORT_SYMBOL(arpt_do_table); module_init(arp_tables_init); module_exit(arp_tables_fini);
static inline bool unconditional(const struct arpt_arp *arp) { static const struct arpt_arp uncond; return memcmp(arp, &uncond, sizeof(uncond)) == 0; }
static inline bool unconditional(const struct arpt_entry *e) { static const struct arpt_arp uncond; return e->target_offset == sizeof(struct arpt_entry) && memcmp(&e->arp, &uncond, sizeof(uncond)) == 0; }
{'added': [(362, 'static inline bool unconditional(const struct arpt_entry *e)'), (366, '\treturn e->target_offset == sizeof(struct arpt_entry) &&'), (367, '\t memcmp(&e->arp, &uncond, sizeof(uncond)) == 0;'), (406, '\t\t\tif ((unconditional(e) &&'), (409, '\t\t\t t->verdict < 0) || visited) {'), (554, '\tif (!unconditional(e))'), (601, '\t\t\t\tpr_debug("Underflows must be unconditional and "'), (602, '\t\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t\t "ACCEPT/DROP\\n");')], 'deleted': [(362, 'static inline bool unconditional(const struct arpt_arp *arp)'), (366, '\treturn memcmp(arp, &uncond, sizeof(uncond)) == 0;'), (405, '\t\t\tif ((e->target_offset == sizeof(struct arpt_entry) &&'), (408, '\t\t\t t->verdict < 0 && unconditional(&e->arp)) ||'), (409, '\t\t\t visited) {'), (554, '\tif (!unconditional(&e->arp))'), (601, '\t\t\t\tpr_err("Underflows must be unconditional and "'), (602, '\t\t\t\t "use the STANDARD target with "'), (603, '\t\t\t\t "ACCEPT/DROP\\n");')]}
9
9
1,537
9,605
https://github.com/torvalds/linux
CVE-2016-3134
['CWE-119']
ua_types_encoding_json.c
WRITE_JSON_ELEMENT
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); }
WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '['); }
{'added': [(111, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (112, ' return UA_STATUSCODE_BADENCODINGERROR;'), (126, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (127, ' return UA_STATUSCODE_BADENCODINGERROR;'), (128, ' ctx->depth++;'), (129, ' ctx->commaNeeded[ctx->depth] = false;'), (1132, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (1390, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (3161, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)')], 'deleted': [(124, ' ctx->commaNeeded[++ctx->depth] = false;'), (1127, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (1385, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (3156, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)')]}
9
4
2,401
17,444
https://github.com/open62541/open62541
CVE-2020-36429
['CWE-787']
ua_types_encoding_json.c
addMultiArrayContentJSON
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; }
addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; }
{'added': [(111, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (112, ' return UA_STATUSCODE_BADENCODINGERROR;'), (126, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (127, ' return UA_STATUSCODE_BADENCODINGERROR;'), (128, ' ctx->depth++;'), (129, ' ctx->commaNeeded[ctx->depth] = false;'), (1132, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (1390, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (3161, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)')], 'deleted': [(124, ' ctx->commaNeeded[++ctx->depth] = false;'), (1127, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (1385, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (3156, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)')]}
9
4
2,401
17,444
https://github.com/open62541/open62541
CVE-2020-36429
['CWE-787']
ua_types_encoding_json.c
decodeJsonStructure
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; }
decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; }
{'added': [(111, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (112, ' return UA_STATUSCODE_BADENCODINGERROR;'), (126, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (127, ' return UA_STATUSCODE_BADENCODINGERROR;'), (128, ' ctx->depth++;'), (129, ' ctx->commaNeeded[ctx->depth] = false;'), (1132, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (1390, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (3161, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)')], 'deleted': [(124, ' ctx->commaNeeded[++ctx->depth] = false;'), (1127, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (1385, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (3156, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)')]}
9
4
2,401
17,444
https://github.com/open62541/open62541
CVE-2020-36429
['CWE-787']
ua_types_encoding_json.c
encodeJsonStructure
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ ctx->commaNeeded[++ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2014-2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer) * Copyright 2018 (c) Fraunhofer IOSB (Author: Lukas Meling) */ #include "ua_types_encoding_json.h" #include <open62541/types_generated.h> #include <open62541/types_generated_handling.h> #include "ua_types_encoding_binary.h" #include <float.h> #include <math.h> #ifdef UA_ENABLE_CUSTOM_LIBC #include "../deps/musl/floatscan.h" #include "../deps/musl/vfprintf.h" #endif #include "../deps/itoa.h" #include "../deps/atoi.h" #include "../deps/string_escape.h" #include "../deps/base64.h" #include "../deps/libc_time.h" #if defined(_MSC_VER) # define strtoll _strtoi64 # define strtoull _strtoui64 #endif /* vs2008 does not have INFINITY and NAN defined */ #ifndef INFINITY # define INFINITY ((UA_Double)(DBL_MAX+DBL_MAX)) #endif #ifndef NAN # define NAN ((UA_Double)(INFINITY-INFINITY)) #endif #if defined(_MSC_VER) # pragma warning(disable: 4756) # pragma warning(disable: 4056) #endif #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0 #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1 #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2 #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40 #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80 #define UA_JSON_DATETIME_LENGTH 30 /* Max length of numbers for the allocation of temp buffers. Don't forget that * printf adds an additional \0 at the end! * * Sources: * https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * * UInt16: 3 + 1 * SByte: 3 + 1 * UInt32: * Int32: * UInt64: * Int64: * Float: 149 + 1 * Double: 767 + 1 */ /************/ /* Encoding */ /************/ #define ENCODE_JSON(TYPE) static status \ TYPE##_encodeJson(const UA_##TYPE *src, const UA_DataType *type, CtxJson *ctx) #define ENCODE_DIRECT_JSON(SRC, TYPE) \ TYPE##_encodeJson((const UA_##TYPE*)SRC, NULL, ctx) extern const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS]; extern const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS]; /* Forward declarations */ UA_String UA_DateTime_toJSON(UA_DateTime t); ENCODE_JSON(ByteString); static status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeChar(CtxJson *ctx, char c) { if(ctx->pos >= ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) *ctx->pos = (UA_Byte)c; ctx->pos++; return UA_STATUSCODE_GOOD; } #define WRITE_JSON_ELEMENT(ELEM) \ UA_FUNC_ATTR_WARN_UNUSED_RESULT status \ writeJson##ELEM(CtxJson *ctx) static WRITE_JSON_ELEMENT(Quote) { return writeChar(ctx, '\"'); } WRITE_JSON_ELEMENT(ObjStart) { /* increase depth, save: before first key-value no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '{'); } WRITE_JSON_ELEMENT(ObjEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, '}'); } WRITE_JSON_ELEMENT(ArrStart) { /* increase depth, save: before first array entry no comma needed. */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; ctx->commaNeeded[ctx->depth] = false; return writeChar(ctx, '['); } WRITE_JSON_ELEMENT(ArrEnd) { ctx->depth--; //decrease depth ctx->commaNeeded[ctx->depth] = true; return writeChar(ctx, ']'); } WRITE_JSON_ELEMENT(CommaIfNeeded) { if(ctx->commaNeeded[ctx->depth]) return writeChar(ctx, ','); return UA_STATUSCODE_GOOD; } status writeJsonArrElm(CtxJson *ctx, const void *value, const UA_DataType *type) { status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; ret |= encodeJsonInternal(value, type, ctx); return ret; } status writeJsonObjElm(CtxJson *ctx, const char *key, const void *value, const UA_DataType *type){ return writeJsonKey(ctx, key) | encodeJsonInternal(value, type, ctx); } status writeJsonNull(CtxJson *ctx) { if(ctx->pos + 4 > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(ctx->calcOnly) { ctx->pos += 4; } else { *(ctx->pos++) = 'n'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 'l'; } return UA_STATUSCODE_GOOD; } /* Keys for JSON */ /* LocalizedText */ static const char* UA_JSONKEY_LOCALE = "Locale"; static const char* UA_JSONKEY_TEXT = "Text"; /* QualifiedName */ static const char* UA_JSONKEY_NAME = "Name"; static const char* UA_JSONKEY_URI = "Uri"; /* NodeId */ static const char* UA_JSONKEY_ID = "Id"; static const char* UA_JSONKEY_IDTYPE = "IdType"; static const char* UA_JSONKEY_NAMESPACE = "Namespace"; /* ExpandedNodeId */ static const char* UA_JSONKEY_SERVERURI = "ServerUri"; /* Variant */ static const char* UA_JSONKEY_TYPE = "Type"; static const char* UA_JSONKEY_BODY = "Body"; static const char* UA_JSONKEY_DIMENSION = "Dimension"; /* DataValue */ static const char* UA_JSONKEY_VALUE = "Value"; static const char* UA_JSONKEY_STATUS = "Status"; static const char* UA_JSONKEY_SOURCETIMESTAMP = "SourceTimestamp"; static const char* UA_JSONKEY_SOURCEPICOSECONDS = "SourcePicoseconds"; static const char* UA_JSONKEY_SERVERTIMESTAMP = "ServerTimestamp"; static const char* UA_JSONKEY_SERVERPICOSECONDS = "ServerPicoseconds"; /* ExtensionObject */ static const char* UA_JSONKEY_ENCODING = "Encoding"; static const char* UA_JSONKEY_TYPEID = "TypeId"; /* StatusCode */ static const char* UA_JSONKEY_CODE = "Code"; static const char* UA_JSONKEY_SYMBOL = "Symbol"; /* DiagnosticInfo */ static const char* UA_JSONKEY_SYMBOLICID = "SymbolicId"; static const char* UA_JSONKEY_NAMESPACEURI = "NamespaceUri"; static const char* UA_JSONKEY_LOCALIZEDTEXT = "LocalizedText"; static const char* UA_JSONKEY_ADDITIONALINFO = "AdditionalInfo"; static const char* UA_JSONKEY_INNERSTATUSCODE = "InnerStatusCode"; static const char* UA_JSONKEY_INNERDIAGNOSTICINFO = "InnerDiagnosticInfo"; /* Writes null terminated string to output buffer (current ctx->pos). Writes * comma in front of key if needed. Encapsulates key in quotes. */ status UA_FUNC_ATTR_WARN_UNUSED_RESULT writeJsonKey(CtxJson *ctx, const char* key) { size_t size = strlen(key); if(ctx->pos + size + 4 > ctx->end) /* +4 because of " " : and , */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonCommaIfNeeded(ctx); ctx->commaNeeded[ctx->depth] = true; if(ctx->calcOnly) { ctx->commaNeeded[ctx->depth] = true; ctx->pos += 3; ctx->pos += size; return ret; } ret |= writeChar(ctx, '\"'); for(size_t i = 0; i < size; i++) { *(ctx->pos++) = (u8)key[i]; } ret |= writeChar(ctx, '\"'); ret |= writeChar(ctx, ':'); return ret; } /* Boolean */ ENCODE_JSON(Boolean) { size_t sizeOfJSONBool; if(*src == true) { sizeOfJSONBool = 4; /*"true"*/ } else { sizeOfJSONBool = 5; /*"false"*/ } if(ctx->calcOnly) { ctx->pos += sizeOfJSONBool; return UA_STATUSCODE_GOOD; } if(ctx->pos + sizeOfJSONBool > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(*src) { *(ctx->pos++) = 't'; *(ctx->pos++) = 'r'; *(ctx->pos++) = 'u'; *(ctx->pos++) = 'e'; } else { *(ctx->pos++) = 'f'; *(ctx->pos++) = 'a'; *(ctx->pos++) = 'l'; *(ctx->pos++) = 's'; *(ctx->pos++) = 'e'; } return UA_STATUSCODE_GOOD; } /*****************/ /* Integer Types */ /*****************/ /* Byte */ ENCODE_JSON(Byte) { char buf[4]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); /* Ensure destination can hold the data- */ if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; /* Copy digits to the output string/buffer. */ if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* signed Byte */ ENCODE_JSON(SByte) { char buf[5]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt16 */ ENCODE_JSON(UInt16) { char buf[6]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int16 */ ENCODE_JSON(Int16) { char buf[7]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt32 */ ENCODE_JSON(UInt32) { char buf[11]; UA_UInt16 digits = itoaUnsigned(*src, buf, 10); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* Int32 */ ENCODE_JSON(Int32) { char buf[12]; UA_UInt16 digits = itoaSigned(*src, buf); if(ctx->pos + digits > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, digits); ctx->pos += digits; return UA_STATUSCODE_GOOD; } /* UInt64 */ ENCODE_JSON(UInt64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaUnsigned(*src, buf + 1, 10); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /* Int64 */ ENCODE_JSON(Int64) { char buf[23]; buf[0] = '\"'; UA_UInt16 digits = itoaSigned(*src, buf + 1); buf[digits + 1] = '\"'; UA_UInt16 length = (UA_UInt16)(digits + 2); if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buf, length); ctx->pos += length; return UA_STATUSCODE_GOOD; } /************************/ /* Floating Point Types */ /************************/ /* Convert special numbers to string * - fmt_fp gives NAN, nan,-NAN, -nan, inf, INF, -inf, -INF * - Special floating-point numbers such as positive infinity (INF), negative * infinity (-INF) and not-a-number (NaN) shall be represented by the values * “Infinity”, “-Infinity” and “NaN” encoded as a JSON string. */ static status checkAndEncodeSpecialFloatingPoint(char *buffer, size_t *len) { /*nan and NaN*/ if(*len == 3 && (buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'a' || buffer[1] == 'A') && (buffer[2] == 'n' || buffer[2] == 'N')) { *len = 5; memcpy(buffer, "\"NaN\"", *len); return UA_STATUSCODE_GOOD; } /*-nan and -NaN*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'a' || buffer[2] == 'A') && (buffer[3] == 'n' || buffer[3] == 'N')) { *len = 6; memcpy(buffer, "\"-NaN\"", *len); return UA_STATUSCODE_GOOD; } /*inf*/ if(*len == 3 && (buffer[0] == 'i' || buffer[0] == 'I') && (buffer[1] == 'n' || buffer[1] == 'N') && (buffer[2] == 'f' || buffer[2] == 'F')) { *len = 10; memcpy(buffer, "\"Infinity\"", *len); return UA_STATUSCODE_GOOD; } /*-inf*/ if(*len == 4 && buffer[0] == '-' && (buffer[1] == 'i' || buffer[1] == 'I') && (buffer[2] == 'n' || buffer[2] == 'N') && (buffer[3] == 'f' || buffer[3] == 'F')) { *len = 11; memcpy(buffer, "\"-Infinity\"", *len); return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_GOOD; } ENCODE_JSON(Float) { char buffer[200]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, -1, 0, 'g'); #else UA_snprintf(buffer, 200, "%.149g", (UA_Double)*src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); if(len == 0) return UA_STATUSCODE_BADENCODINGERROR; checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } ENCODE_JSON(Double) { char buffer[2000]; if(*src == *src) { #ifdef UA_ENABLE_CUSTOM_LIBC fmt_fp(buffer, *src, 0, 17, 0, 'g'); #else UA_snprintf(buffer, 2000, "%.1074g", *src); #endif } else { strcpy(buffer, "NaN"); } size_t len = strlen(buffer); checkAndEncodeSpecialFloatingPoint(buffer, &len); if(ctx->pos + len > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, buffer, len); ctx->pos += len; return UA_STATUSCODE_GOOD; } static status encodeJsonArray(CtxJson *ctx, const void *ptr, size_t length, const UA_DataType *type) { encodeJsonSignature encodeType = encodeJsonJumpTable[type->typeKind]; status ret = writeJsonArrStart(ctx); uintptr_t uptr = (uintptr_t)ptr; for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { ret |= writeJsonCommaIfNeeded(ctx); ret |= encodeType((const void*)uptr, type, ctx); ctx->commaNeeded[ctx->depth] = true; uptr += type->memSize; } ret |= writeJsonArrEnd(ctx); return ret; } /*****************/ /* Builtin Types */ /*****************/ static const u8 hexmapLower[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; static const u8 hexmapUpper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; ENCODE_JSON(String) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } UA_StatusCode ret = writeJsonQuote(ctx); /* Escaping adapted from https://github.com/akheron/jansson dump.c */ const char *str = (char*)src->data; const char *pos = str; const char *end = str; const char *lim = str + src->length; UA_UInt32 codepoint = 0; while(1) { const char *text; u8 seq[13]; size_t length; while(end < lim) { end = utf8_iterate(pos, (size_t)(lim - pos), (int32_t *)&codepoint); if(!end) return UA_STATUSCODE_BADENCODINGERROR; /* mandatory escape or control char */ if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20) break; /* TODO: Why is this commented? */ /* slash if((flags & JSON_ESCAPE_SLASH) && codepoint == '/') break;*/ /* non-ASCII if((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F) break;*/ pos = end; } if(pos != str) { if(ctx->pos + (pos - str) > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, str, (size_t)(pos - str)); ctx->pos += pos - str; } if(end == pos) break; /* handle \, /, ", and control codes */ length = 2; switch(codepoint) { case '\\': text = "\\\\"; break; case '\"': text = "\\\""; break; case '\b': text = "\\b"; break; case '\f': text = "\\f"; break; case '\n': text = "\\n"; break; case '\r': text = "\\r"; break; case '\t': text = "\\t"; break; case '/': text = "\\/"; break; default: if(codepoint < 0x10000) { /* codepoint is in BMP */ seq[0] = '\\'; seq[1] = 'u'; UA_Byte b1 = (UA_Byte)(codepoint >> 8u); UA_Byte b2 = (UA_Byte)(codepoint >> 0u); seq[2] = hexmapLower[(b1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[b1 & 0x0Fu]; seq[4] = hexmapLower[(b2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[b2 & 0x0Fu]; length = 6; } else { /* not in BMP -> construct a UTF-16 surrogate pair */ codepoint -= 0x10000; UA_UInt32 first = 0xD800u | ((codepoint & 0xffc00u) >> 10u); UA_UInt32 last = 0xDC00u | (codepoint & 0x003ffu); UA_Byte fb1 = (UA_Byte)(first >> 8u); UA_Byte fb2 = (UA_Byte)(first >> 0u); UA_Byte lb1 = (UA_Byte)(last >> 8u); UA_Byte lb2 = (UA_Byte)(last >> 0u); seq[0] = '\\'; seq[1] = 'u'; seq[2] = hexmapLower[(fb1 & 0xF0u) >> 4u]; seq[3] = hexmapLower[fb1 & 0x0Fu]; seq[4] = hexmapLower[(fb2 & 0xF0u) >> 4u]; seq[5] = hexmapLower[fb2 & 0x0Fu]; seq[6] = '\\'; seq[7] = 'u'; seq[8] = hexmapLower[(lb1 & 0xF0u) >> 4u]; seq[9] = hexmapLower[lb1 & 0x0Fu]; seq[10] = hexmapLower[(lb2 & 0xF0u) >> 4u]; seq[11] = hexmapLower[lb2 & 0x0Fu]; length = 12; } text = (char*)seq; break; } if(ctx->pos + length > ctx->end) return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; if(!ctx->calcOnly) memcpy(ctx->pos, text, length); ctx->pos += length; str = pos = end; } ret |= writeJsonQuote(ctx); return ret; } ENCODE_JSON(ByteString) { if(!src->data) return writeJsonNull(ctx); if(src->length == 0) { status retval = writeJsonQuote(ctx); retval |= writeJsonQuote(ctx); return retval; } status ret = writeJsonQuote(ctx); size_t flen = 0; unsigned char *ba64 = UA_base64(src->data, src->length, &flen); /* Not converted, no mem */ if(!ba64) return UA_STATUSCODE_BADENCODINGERROR; if(ctx->pos + flen > ctx->end) { UA_free(ba64); return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; } /* Copy flen bytes to output stream. */ if(!ctx->calcOnly) memcpy(ctx->pos, ba64, flen); ctx->pos += flen; /* Base64 result no longer needed */ UA_free(ba64); ret |= writeJsonQuote(ctx); return ret; } /* Converts Guid to a hexadecimal represenation */ static void UA_Guid_to_hex(const UA_Guid *guid, u8* out) { /* 16 byte +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | data1 |data2|data3| data4 | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |aa aa aa aa-bb bb-cc cc-dd dd-ee ee ee ee ee ee| +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 36 character */ #ifdef hexCharlowerCase const u8 *hexmap = hexmapLower; #else const u8 *hexmap = hexmapUpper; #endif size_t i = 0, j = 28; for(; i<8;i++,j-=4) /* pos 0-7, 4byte, (a) */ out[i] = hexmap[(guid->data1 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 8 */ for(j=12; i<13;i++,j-=4) /* pos 9-12, 2byte, (b) */ out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 13 */ for(j=12; i<18;i++,j-=4) /* pos 14-17, 2byte (c) */ out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu]; out[i++] = '-'; /* pos 18 */ for(j=0;i<23;i+=2,j++) { /* pos 19-22, 2byte (d) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } out[i++] = '-'; /* pos 23 */ for(j=2; i<36;i+=2,j++) { /* pos 24-35, 6byte (e) */ out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u]; out[i+1] = hexmap[guid->data4[j] & 0x0Fu]; } } /* Guid */ ENCODE_JSON(Guid) { if(ctx->pos + 38 > ctx->end) /* 36 + 2 (") */ return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED; status ret = writeJsonQuote(ctx); u8 *buf = ctx->pos; if(!ctx->calcOnly) UA_Guid_to_hex(src, buf); ctx->pos += 36; ret |= writeJsonQuote(ctx); return ret; } static void printNumber(u16 n, u8 *pos, size_t digits) { for(size_t i = digits; i > 0; --i) { pos[i - 1] = (u8) ((n % 10) + '0'); n = n / 10; } } ENCODE_JSON(DateTime) { UA_DateTimeStruct tSt = UA_DateTime_toStruct(*src); /* Format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z' is used. max 30 bytes.*/ UA_Byte buffer[UA_JSON_DATETIME_LENGTH]; printNumber(tSt.year, &buffer[0], 4); buffer[4] = '-'; printNumber(tSt.month, &buffer[5], 2); buffer[7] = '-'; printNumber(tSt.day, &buffer[8], 2); buffer[10] = 'T'; printNumber(tSt.hour, &buffer[11], 2); buffer[13] = ':'; printNumber(tSt.min, &buffer[14], 2); buffer[16] = ':'; printNumber(tSt.sec, &buffer[17], 2); buffer[19] = '.'; printNumber(tSt.milliSec, &buffer[20], 3); printNumber(tSt.microSec, &buffer[23], 3); printNumber(tSt.nanoSec, &buffer[26], 3); size_t length = 28; while (buffer[length] == '0') length--; if (length != 19) length++; buffer[length] = 'Z'; UA_String str = {length + 1, buffer}; return ENCODE_DIRECT_JSON(&str, String); } /* NodeId */ static status NodeId_encodeJsonInternal(UA_NodeId const *src, CtxJson *ctx) { status ret = UA_STATUSCODE_GOOD; switch (src->identifierType) { case UA_NODEIDTYPE_NUMERIC: ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.numeric, UInt32); break; case UA_NODEIDTYPE_STRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '1'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); ret |= ENCODE_DIRECT_JSON(&src->identifier.string, String); break; case UA_NODEIDTYPE_GUID: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '2'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.guid, Guid); break; case UA_NODEIDTYPE_BYTESTRING: ret |= writeJsonKey(ctx, UA_JSONKEY_IDTYPE); ret |= writeChar(ctx, '3'); ret |= writeJsonKey(ctx, UA_JSONKEY_ID); /* Id */ ret |= ENCODE_DIRECT_JSON(&src->identifier.byteString, ByteString); break; default: return UA_STATUSCODE_BADINTERNALERROR; } return ret; } ENCODE_JSON(NodeId) { UA_StatusCode ret = writeJsonObjStart(ctx); ret |= NodeId_encodeJsonInternal(src, ctx); if(ctx->useReversible) { if(src->namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible encoding, the field is the NamespaceUri * associated with the NamespaceIndex, encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } } } ret |= writeJsonObjEnd(ctx); return ret; } /* ExpandedNodeId */ ENCODE_JSON(ExpandedNodeId) { status ret = writeJsonObjStart(ctx); /* Encode the NodeId */ ret |= NodeId_encodeJsonInternal(&src->nodeId, ctx); if(ctx->useReversible) { if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0 && (void*) src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) { /* If the NamespaceUri is specified it is encoded as a JSON string in this field. */ ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); } else { /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * The field is encoded as a JSON number for the reversible encoding. * The field is omitted if the NamespaceIndex equals 0. */ if(src->nodeId.namespaceIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); } } /* Encode the serverIndex/Url * This field is encoded as a JSON number for the reversible encoding. * This field is omitted if the ServerIndex equals 0. */ if(src->serverIndex > 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&src->serverIndex, UInt32); } ret |= writeJsonObjEnd(ctx); return ret; } /* NON-Reversible Case */ /* If the NamespaceUri is not specified, the NamespaceIndex is encoded with these rules: * For the non-reversible encoding the field is the NamespaceUri associated with the * NamespaceIndex encoded as a JSON string. * A NamespaceIndex of 1 is always encoded as a JSON number. */ if(src->namespaceUri.data != NULL && src->namespaceUri.length != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { if(src->nodeId.namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); ret |= ENCODE_DIRECT_JSON(&src->nodeId.namespaceIndex, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } else { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACE); /* Check if Namespace given and in range */ if(src->nodeId.namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->nodeId.namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); if(ret != UA_STATUSCODE_GOOD) return ret; } else { return UA_STATUSCODE_BADNOTFOUND; } } } /* For the non-reversible encoding, this field is the ServerUri associated * with the ServerIndex portion of the ExpandedNodeId, encoded as a JSON * string. */ /* Check if Namespace given and in range */ if(src->serverIndex < ctx->serverUrisSize && ctx->serverUris != NULL) { UA_String serverUriEntry = ctx->serverUris[src->serverIndex]; ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERURI); ret |= ENCODE_DIRECT_JSON(&serverUriEntry, String); } else { return UA_STATUSCODE_BADNOTFOUND; } ret |= writeJsonObjEnd(ctx); return ret; } /* LocalizedText */ ENCODE_JSON(LocalizedText) { if(ctx->useReversible) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, String); ret |= writeJsonKey(ctx, UA_JSONKEY_TEXT); ret |= ENCODE_DIRECT_JSON(&src->text, String); ret |= writeJsonObjEnd(ctx); return ret; } /* For the non-reversible form, LocalizedText value shall be encoded as a * JSON string containing the Text component.*/ return ENCODE_DIRECT_JSON(&src->text, String); } ENCODE_JSON(QualifiedName) { status ret = writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_NAME); ret |= ENCODE_DIRECT_JSON(&src->name, String); if(ctx->useReversible) { if(src->namespaceIndex != 0) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } else { /* For the non-reversible form, the NamespaceUri associated with the * NamespaceIndex portion of the QualifiedName is encoded as JSON string * unless the NamespaceIndex is 1 or if NamespaceUri is unknown. In * these cases, the NamespaceIndex is encoded as a JSON number. */ if(src->namespaceIndex == 1) { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } else { ret |= writeJsonKey(ctx, UA_JSONKEY_URI); /* Check if Namespace given and in range */ if(src->namespaceIndex < ctx->namespacesSize && ctx->namespaces != NULL) { UA_String namespaceEntry = ctx->namespaces[src->namespaceIndex]; ret |= ENCODE_DIRECT_JSON(&namespaceEntry, String); } else { /* If not encode as number */ ret |= ENCODE_DIRECT_JSON(&src->namespaceIndex, UInt16); } } } return ret | writeJsonObjEnd(ctx); } ENCODE_JSON(StatusCode) { if(!src) return writeJsonNull(ctx); if(ctx->useReversible) return ENCODE_DIRECT_JSON(src, UInt32); if(*src == UA_STATUSCODE_GOOD) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); ret |= writeJsonKey(ctx, UA_JSONKEY_CODE); ret |= ENCODE_DIRECT_JSON(src, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOL); const char *codename = UA_StatusCode_name(*src); UA_String statusDescription = UA_STRING((char*)(uintptr_t)codename); ret |= ENCODE_DIRECT_JSON(&statusDescription, String); ret |= writeJsonObjEnd(ctx); return ret; } /* ExtensionObject */ ENCODE_JSON(ExtensionObject) { u8 encoding = (u8) src->encoding; if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) return writeJsonNull(ctx); status ret = UA_STATUSCODE_GOOD; /* already encoded content.*/ if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) { ret |= writeJsonObjStart(ctx); if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.typeId, NodeId); if(ret != UA_STATUSCODE_GOOD) return ret; } switch (src->encoding) { case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '1'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } case UA_EXTENSIONOBJECT_ENCODED_XML: { if(ctx->useReversible) { ret |= writeJsonKey(ctx, UA_JSONKEY_ENCODING); ret |= writeChar(ctx, '2'); } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= ENCODE_DIRECT_JSON(&src->content.encoded.body, String); break; } default: ret = UA_STATUSCODE_BADINTERNALERROR; } ret |= writeJsonObjEnd(ctx); return ret; } /* encoding <= UA_EXTENSIONOBJECT_ENCODED_XML */ /* Cannot encode with no type description */ if(!src->content.decoded.type) return UA_STATUSCODE_BADENCODINGERROR; if(!src->content.decoded.data) return writeJsonNull(ctx); UA_NodeId typeId = src->content.decoded.type->typeId; if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC) return UA_STATUSCODE_BADENCODINGERROR; ret |= writeJsonObjStart(ctx); const UA_DataType *contentType = src->content.decoded.type; if(ctx->useReversible) { /* REVERSIBLE */ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPEID); ret |= ENCODE_DIRECT_JSON(&typeId, NodeId); /* Encode the content */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } else { /* NON-REVERSIBLE * For the non-reversible form, ExtensionObject values * shall be encoded as a JSON object containing only the * value of the Body field. The TypeId and Encoding fields are dropped. * * TODO: UA_JSONKEY_BODY key in the ExtensionObject? */ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->content.decoded.data, contentType, ctx); } ret |= writeJsonObjEnd(ctx); return ret; } static status Variant_encodeJsonWrapExtensionObject(const UA_Variant *src, const bool isArray, CtxJson *ctx) { size_t length = 1; status ret = UA_STATUSCODE_GOOD; if(isArray) { if(src->arrayLength > UA_INT32_MAX) return UA_STATUSCODE_BADENCODINGERROR; length = src->arrayLength; } /* Set up the ExtensionObject */ UA_ExtensionObject eo; UA_ExtensionObject_init(&eo); eo.encoding = UA_EXTENSIONOBJECT_DECODED; eo.content.decoded.type = src->type; const u16 memSize = src->type->memSize; uintptr_t ptr = (uintptr_t) src->data; if(isArray) { ret |= writeJsonArrStart(ctx); ctx->commaNeeded[ctx->depth] = false; /* Iterate over the array */ for(size_t i = 0; i < length && ret == UA_STATUSCODE_GOOD; ++i) { eo.content.decoded.data = (void*) ptr; ret |= writeJsonArrElm(ctx, &eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]); ptr += memSize; } ret |= writeJsonArrEnd(ctx); return ret; } eo.content.decoded.data = (void*) ptr; return encodeJsonInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT], ctx); } static status addMultiArrayContentJSON(CtxJson *ctx, void* array, const UA_DataType *type, size_t *index, UA_UInt32 *arrayDimensions, size_t dimensionIndex, size_t dimensionSize) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; /* Stop recursion: The inner Arrays are written */ status ret; if(dimensionIndex == (dimensionSize - 1)) { ret = encodeJsonArray(ctx, ((u8*)array) + (type->memSize * *index), arrayDimensions[dimensionIndex], type); (*index) += arrayDimensions[dimensionIndex]; return ret; } /* Recurse to the next dimension */ ret = writeJsonArrStart(ctx); for(size_t i = 0; i < arrayDimensions[dimensionIndex]; i++) { ret |= writeJsonCommaIfNeeded(ctx); ret |= addMultiArrayContentJSON(ctx, array, type, index, arrayDimensions, dimensionIndex + 1, dimensionSize); ctx->commaNeeded[ctx->depth] = true; if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonArrEnd(ctx); return ret; } ENCODE_JSON(Variant) { /* If type is 0 (NULL) the Variant contains a NULL value and the containing * JSON object shall be omitted or replaced by the JSON literal ‘null’ (when * an element of a JSON array). */ if(!src->type) { return writeJsonNull(ctx); } /* Set the content type in the encoding mask */ const UA_Boolean isBuiltin = (src->type->typeKind <= UA_DATATYPEKIND_DIAGNOSTICINFO); const UA_Boolean isEnum = (src->type->typeKind == UA_DATATYPEKIND_ENUM); /* Set the array type in the encoding mask */ const bool isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL; const bool hasDimensions = isArray && src->arrayDimensionsSize > 0; status ret = UA_STATUSCODE_GOOD; if(ctx->useReversible) { ret |= writeJsonObjStart(ctx); if(ret != UA_STATUSCODE_GOOD) return ret; /* Encode the content */ if(!isBuiltin && !isEnum) { /* REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&UA_TYPES[UA_TYPES_EXTENSIONOBJECT].typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_TYPE); ret |= ENCODE_DIRECT_JSON(&src->type->typeId.identifier.numeric, UInt32); ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } if(ret != UA_STATUSCODE_GOOD) return ret; /* REVERSIBLE: Encode the array dimensions */ if(hasDimensions && ret == UA_STATUSCODE_GOOD) { ret |= writeJsonKey(ctx, UA_JSONKEY_DIMENSION); ret |= encodeJsonArray(ctx, src->arrayDimensions, src->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* reversible */ /* NON-REVERSIBLE * For the non-reversible form, Variant values shall be encoded as a JSON object containing only * the value of the Body field. The Type and Dimensions fields are dropped. Multi-dimensional * arrays are encoded as a multi dimensional JSON array as described in 5.4.5. */ ret |= writeJsonObjStart(ctx); if(!isBuiltin && !isEnum) { /*NON REVERSIBLE: NOT BUILTIN, can it be encoded? Wrap in extension object.*/ if(src->arrayDimensionsSize > 1) { return UA_STATUSCODE_BADNOTIMPLEMENTED; } ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= Variant_encodeJsonWrapExtensionObject(src, isArray, ctx); } else if(!isArray) { /*NON REVERSIBLE: BUILTIN, single value.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); ret |= encodeJsonInternal(src->data, src->type, ctx); } else { /*NON REVERSIBLE: BUILTIN, array.*/ ret |= writeJsonKey(ctx, UA_JSONKEY_BODY); size_t dimensionSize = src->arrayDimensionsSize; if(dimensionSize > 1) { /*nonreversible multidimensional array*/ size_t index = 0; size_t dimensionIndex = 0; void *ptr = src->data; const UA_DataType *arraytype = src->type; ret |= addMultiArrayContentJSON(ctx, ptr, arraytype, &index, src->arrayDimensions, dimensionIndex, dimensionSize); } else { /*nonreversible simple array*/ ret |= encodeJsonArray(ctx, src->data, src->arrayLength, src->type); } } ret |= writeJsonObjEnd(ctx); return ret; } /* DataValue */ ENCODE_JSON(DataValue) { UA_Boolean hasValue = src->hasValue && src->value.type != NULL; UA_Boolean hasStatus = src->hasStatus && src->status; UA_Boolean hasSourceTimestamp = src->hasSourceTimestamp && src->sourceTimestamp; UA_Boolean hasSourcePicoseconds = src->hasSourcePicoseconds && src->sourcePicoseconds; UA_Boolean hasServerTimestamp = src->hasServerTimestamp && src->serverTimestamp; UA_Boolean hasServerPicoseconds = src->hasServerPicoseconds && src->serverPicoseconds; if(!hasValue && !hasStatus && !hasSourceTimestamp && !hasSourcePicoseconds && !hasServerTimestamp && !hasServerPicoseconds) { return writeJsonNull(ctx); /*no element, encode as null*/ } status ret = UA_STATUSCODE_GOOD; ret |= writeJsonObjStart(ctx); if(hasValue) { ret |= writeJsonKey(ctx, UA_JSONKEY_VALUE); ret |= ENCODE_DIRECT_JSON(&src->value, Variant); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasStatus) { ret |= writeJsonKey(ctx, UA_JSONKEY_STATUS); ret |= ENCODE_DIRECT_JSON(&src->status, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourceTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCETIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->sourceTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasSourcePicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SOURCEPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->sourcePicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerTimestamp) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERTIMESTAMP); ret |= ENCODE_DIRECT_JSON(&src->serverTimestamp, DateTime); if(ret != UA_STATUSCODE_GOOD) return ret; } if(hasServerPicoseconds) { ret |= writeJsonKey(ctx, UA_JSONKEY_SERVERPICOSECONDS); ret |= ENCODE_DIRECT_JSON(&src->serverPicoseconds, UInt16); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } /* DiagnosticInfo */ ENCODE_JSON(DiagnosticInfo) { status ret = UA_STATUSCODE_GOOD; if(!src->hasSymbolicId && !src->hasNamespaceUri && !src->hasLocalizedText && !src->hasLocale && !src->hasAdditionalInfo && !src->hasInnerDiagnosticInfo && !src->hasInnerStatusCode) { return writeJsonNull(ctx); /*no element present, encode as null.*/ } ret |= writeJsonObjStart(ctx); if(src->hasSymbolicId) { ret |= writeJsonKey(ctx, UA_JSONKEY_SYMBOLICID); ret |= ENCODE_DIRECT_JSON(&src->symbolicId, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasNamespaceUri) { ret |= writeJsonKey(ctx, UA_JSONKEY_NAMESPACEURI); ret |= ENCODE_DIRECT_JSON(&src->namespaceUri, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocalizedText) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALIZEDTEXT); ret |= ENCODE_DIRECT_JSON(&src->localizedText, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasLocale) { ret |= writeJsonKey(ctx, UA_JSONKEY_LOCALE); ret |= ENCODE_DIRECT_JSON(&src->locale, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasAdditionalInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_ADDITIONALINFO); ret |= ENCODE_DIRECT_JSON(&src->additionalInfo, String); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerStatusCode) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERSTATUSCODE); ret |= ENCODE_DIRECT_JSON(&src->innerStatusCode, StatusCode); if(ret != UA_STATUSCODE_GOOD) return ret; } if(src->hasInnerDiagnosticInfo && src->innerDiagnosticInfo) { ret |= writeJsonKey(ctx, UA_JSONKEY_INNERDIAGNOSTICINFO); /* Check recursion depth in encodeJsonInternal */ ret |= encodeJsonInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO], ctx); if(ret != UA_STATUSCODE_GOOD) return ret; } ret |= writeJsonObjEnd(ctx); return ret; } static status encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; } static status encodeJsonNotImplemented(const void *src, const UA_DataType *type, CtxJson *ctx) { (void) src, (void) type, (void)ctx; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const encodeJsonSignature encodeJsonJumpTable[UA_DATATYPEKINDS] = { (encodeJsonSignature)Boolean_encodeJson, (encodeJsonSignature)SByte_encodeJson, /* SByte */ (encodeJsonSignature)Byte_encodeJson, (encodeJsonSignature)Int16_encodeJson, /* Int16 */ (encodeJsonSignature)UInt16_encodeJson, (encodeJsonSignature)Int32_encodeJson, /* Int32 */ (encodeJsonSignature)UInt32_encodeJson, (encodeJsonSignature)Int64_encodeJson, /* Int64 */ (encodeJsonSignature)UInt64_encodeJson, (encodeJsonSignature)Float_encodeJson, (encodeJsonSignature)Double_encodeJson, (encodeJsonSignature)String_encodeJson, (encodeJsonSignature)DateTime_encodeJson, /* DateTime */ (encodeJsonSignature)Guid_encodeJson, (encodeJsonSignature)ByteString_encodeJson, /* ByteString */ (encodeJsonSignature)String_encodeJson, /* XmlElement */ (encodeJsonSignature)NodeId_encodeJson, (encodeJsonSignature)ExpandedNodeId_encodeJson, (encodeJsonSignature)StatusCode_encodeJson, /* StatusCode */ (encodeJsonSignature)QualifiedName_encodeJson, /* QualifiedName */ (encodeJsonSignature)LocalizedText_encodeJson, (encodeJsonSignature)ExtensionObject_encodeJson, (encodeJsonSignature)DataValue_encodeJson, (encodeJsonSignature)Variant_encodeJson, (encodeJsonSignature)DiagnosticInfo_encodeJson, (encodeJsonSignature)encodeJsonNotImplemented, /* Decimal */ (encodeJsonSignature)Int32_encodeJson, /* Enum */ (encodeJsonSignature)encodeJsonStructure, (encodeJsonSignature)encodeJsonNotImplemented, /* Structure with optional fields */ (encodeJsonSignature)encodeJsonNotImplemented, /* Union */ (encodeJsonSignature)encodeJsonNotImplemented /* BitfieldCluster */ }; status encodeJsonInternal(const void *src, const UA_DataType *type, CtxJson *ctx) { return encodeJsonJumpTable[type->typeKind](src, type, ctx); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_encodeJson(const void *src, const UA_DataType *type, u8 **bufPos, const u8 **bufEnd, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = *bufPos; ctx.end = *bufEnd; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = false; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); *bufPos = ctx.pos; *bufEnd = ctx.end; return ret; } /************/ /* CalcSize */ /************/ size_t UA_calcSizeJson(const void *src, const UA_DataType *type, UA_String *namespaces, size_t namespaceSize, UA_String *serverUris, size_t serverUriSize, UA_Boolean useReversible) { if(!src || !type) return UA_STATUSCODE_BADINTERNALERROR; /* Set up the context */ CtxJson ctx; memset(&ctx, 0, sizeof(ctx)); ctx.pos = 0; ctx.end = (const UA_Byte*)(uintptr_t)SIZE_MAX; ctx.depth = 0; ctx.namespaces = namespaces; ctx.namespacesSize = namespaceSize; ctx.serverUris = serverUris; ctx.serverUrisSize = serverUriSize; ctx.useReversible = useReversible; ctx.calcOnly = true; /* Encode */ status ret = encodeJsonJumpTable[type->typeKind](src, type, &ctx); if(ret != UA_STATUSCODE_GOOD) return 0; return (size_t)ctx.pos; } /**********/ /* Decode */ /**********/ /* Macro which gets current size and char pointer of current Token. Needs * ParseCtx (parseCtx) and CtxJson (ctx). Does NOT increment index of Token. */ #define GET_TOKEN(data, size) do { \ (size) = (size_t)(parseCtx->tokenArray[parseCtx->index].end - parseCtx->tokenArray[parseCtx->index].start); \ (data) = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); } while(0) #define ALLOW_NULL do { \ if(isJsonNull(ctx, parseCtx)) { \ parseCtx->index++; \ return UA_STATUSCODE_GOOD; \ }} while(0) #define CHECK_TOKEN_BOUNDS do { \ if(parseCtx->index >= parseCtx->tokenCount) \ return UA_STATUSCODE_BADDECODINGERROR; \ } while(0) #define CHECK_PRIMITIVE do { \ if(getJsmnType(parseCtx) != JSMN_PRIMITIVE) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_STRING do { \ if(getJsmnType(parseCtx) != JSMN_STRING) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) #define CHECK_OBJECT do { \ if(getJsmnType(parseCtx) != JSMN_OBJECT) { \ return UA_STATUSCODE_BADDECODINGERROR; \ }} while(0) /* Forward declarations*/ #define DECODE_JSON(TYPE) static status \ TYPE##_decodeJson(UA_##TYPE *dst, const UA_DataType *type, \ CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) /* decode without moving the token index */ #define DECODE_DIRECT_JSON(DST, TYPE) TYPE##_decodeJson((UA_##TYPE*)DST, NULL, ctx, parseCtx, false) /* If parseCtx->index points to the beginning of an object, move the index to * the next token after this object. Attention! The index can be moved after the * last parsed token. So the array length has to be checked afterwards. */ static void skipObject(ParseCtx *parseCtx) { int end = parseCtx->tokenArray[parseCtx->index].end; do { parseCtx->index++; } while(parseCtx->index < parseCtx->tokenCount && parseCtx->tokenArray[parseCtx->index].start < end); } static status Array_decodeJson(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken); /* Json decode Helper */ jsmntype_t getJsmnType(const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return JSMN_UNDEFINED; return parseCtx->tokenArray[parseCtx->index].type; } UA_Boolean isJsonNull(const CtxJson *ctx, const ParseCtx *parseCtx) { if(parseCtx->index >= parseCtx->tokenCount) return false; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_PRIMITIVE) { return false; } char* elem = (char*)(ctx->pos + parseCtx->tokenArray[parseCtx->index].start); return (elem[0] == 'n' && elem[1] == 'u' && elem[2] == 'l' && elem[3] == 'l'); } static UA_SByte jsoneq(const char *json, jsmntok_t *tok, const char *searchKey) { /* TODO: necessary? if(json == NULL || tok == NULL || searchKey == NULL) { return -1; } */ if(tok->type == JSMN_STRING) { if(strlen(searchKey) == (size_t)(tok->end - tok->start) ) { if(strncmp(json + tok->start, (const char*)searchKey, (size_t)(tok->end - tok->start)) == 0) { return 0; } } } return -1; } DECODE_JSON(Boolean) { CHECK_PRIMITIVE; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize == 4 && tokenData[0] == 't' && tokenData[1] == 'r' && tokenData[2] == 'u' && tokenData[3] == 'e') { *dst = true; } else if(tokenSize == 5 && tokenData[0] == 'f' && tokenData[1] == 'a' && tokenData[2] == 'l' && tokenData[3] == 's' && tokenData[4] == 'e') { *dst = false; } else { return UA_STATUSCODE_BADDECODINGERROR; } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } #ifdef UA_ENABLE_CUSTOM_LIBC static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { UA_UInt64 d = 0; atoiUnsigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { UA_Int64 d = 0; atoiSigned(inputBuffer, sizeOfBuffer, &d); if(!destinationOfNumber) return UA_STATUSCODE_BADDECODINGERROR; *destinationOfNumber = d; return UA_STATUSCODE_GOOD; } #else /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseUnsignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_UInt64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) { return UA_STATUSCODE_BADDECODINGERROR; } /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer+1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_UInt64 val = strtoull(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LLONG_MAX || val == 0)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } /* Safe strtol variant of unsigned string conversion. * Returns UA_STATUSCODE_BADDECODINGERROR in case of overflows. * Buffer limit is 20 digits. */ static UA_StatusCode parseSignedInteger(char* inputBuffer, size_t sizeOfBuffer, UA_Int64 *destinationOfNumber) { /* Check size to avoid huge malicious stack allocation. * No UInt64 can have more digits than 20. */ if(sizeOfBuffer > 20) return UA_STATUSCODE_BADDECODINGERROR; /* convert to null terminated string */ UA_STACKARRAY(char, string, sizeOfBuffer + 1); memcpy(string, inputBuffer, sizeOfBuffer); string[sizeOfBuffer] = 0; /* Conversion */ char *endptr, *str; str = string; errno = 0; /* To distinguish success/failure after call */ UA_Int64 val = strtoll(str, &endptr, 10); /* Check for various possible errors */ if((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 )) { return UA_STATUSCODE_BADDECODINGERROR; } /* Check if no digits were found */ if(endptr == str) return UA_STATUSCODE_BADDECODINGERROR; /* copy to destination */ *destinationOfNumber = val; return UA_STATUSCODE_GOOD; } #endif DECODE_JSON(Byte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_Byte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(UInt64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_UInt64 out = 0; UA_StatusCode s = parseUnsignedInteger(tokenData, tokenSize, &out); *dst = (UA_UInt64)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(SByte) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_SByte)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int16) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int16)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int32) { CHECK_TOKEN_BOUNDS; CHECK_PRIMITIVE; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int32)out; if(moveToken) parseCtx->index++; return s; } DECODE_JSON(Int64) { CHECK_TOKEN_BOUNDS; CHECK_STRING; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); UA_Int64 out = 0; UA_StatusCode s = parseSignedInteger(tokenData, tokenSize, &out); *dst = (UA_Int64)out; if(moveToken) parseCtx->index++; return s; } static UA_UInt32 hex2int(char ch) { if(ch >= '0' && ch <= '9') return (UA_UInt32)(ch - '0'); if(ch >= 'A' && ch <= 'F') return (UA_UInt32)(ch - 'A' + 10); if(ch >= 'a' && ch <= 'f') return (UA_UInt32)(ch - 'a' + 10); return 0; } /* Float * Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Float) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 149 * Sanity check. */ if(tokenSize > 150) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = (UA_Float)INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = (UA_Float)-INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = (UA_Float)NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Float d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Float)__floatscan(string, 1, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%f%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Either a JSMN_STRING or JSMN_PRIMITIVE */ DECODE_JSON(Double) { CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/ * Maximum digit counts for select IEEE floating-point formats: 1074 * Sanity check. */ if(tokenSize > 1075) return UA_STATUSCODE_BADDECODINGERROR; jsmntype_t tokenType = getJsmnType(parseCtx); if(tokenType == JSMN_STRING) { /*It could be a String with Nan, Infinity*/ if(tokenSize == 8 && memcmp(tokenData, "Infinity", 8) == 0) { *dst = INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 9 && memcmp(tokenData, "-Infinity", 9) == 0) { /* workaround an MSVC 2013 issue */ *dst = -INFINITY; return UA_STATUSCODE_GOOD; } if(tokenSize == 3 && memcmp(tokenData, "NaN", 3) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } if(tokenSize == 4 && memcmp(tokenData, "-NaN", 4) == 0) { *dst = NAN; return UA_STATUSCODE_GOOD; } return UA_STATUSCODE_BADDECODINGERROR; } if(tokenType != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Null-Terminate for sscanf. Should this better be handled on heap? Max * 1075 input chars allowed. Not using heap. */ UA_STACKARRAY(char, string, tokenSize+1); memcpy(string, tokenData, tokenSize); string[tokenSize] = 0; UA_Double d = 0; #ifdef UA_ENABLE_CUSTOM_LIBC d = (UA_Double)__floatscan(string, 2, 0); #else char c = 0; /* On success, the function returns the number of variables filled. * In the case of an input failure before any data could be successfully read, EOF is returned. */ int ret = sscanf(string, "%lf%c", &d, &c); /* Exactly one var must be filled. %c acts as a guard for wrong input which is accepted by sscanf. E.g. 1.23.45 is not accepted. */ if(ret == EOF || (ret != 1)) return UA_STATUSCODE_BADDECODINGERROR; #endif *dst = d; parseCtx->index++; return UA_STATUSCODE_GOOD; } /* Expects 36 chars in format 00000003-0009-000A-0807-060504030201 | data1| |d2| |d3| |d4| | data4 | */ static UA_Guid UA_Guid_fromChars(const char* chars) { UA_Guid dst; UA_Guid_init(&dst); for(size_t i = 0; i < 8; i++) dst.data1 |= (UA_UInt32)(hex2int(chars[i]) << (28 - (i*4))); for(size_t i = 0; i < 4; i++) { dst.data2 |= (UA_UInt16)(hex2int(chars[9+i]) << (12 - (i*4))); dst.data3 |= (UA_UInt16)(hex2int(chars[14+i]) << (12 - (i*4))); } dst.data4[0] |= (UA_Byte)(hex2int(chars[19]) << 4u); dst.data4[0] |= (UA_Byte)(hex2int(chars[20]) << 0u); dst.data4[1] |= (UA_Byte)(hex2int(chars[21]) << 4u); dst.data4[1] |= (UA_Byte)(hex2int(chars[22]) << 0u); for(size_t i = 0; i < 6; i++) { dst.data4[2+i] |= (UA_Byte)(hex2int(chars[24 + i*2]) << 4u); dst.data4[2+i] |= (UA_Byte)(hex2int(chars[25 + i*2]) << 0u); } return dst; } DECODE_JSON(Guid) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); if(tokenSize != 36) return UA_STATUSCODE_BADDECODINGERROR; /* check if incorrect chars are present */ for(size_t i = 0; i < tokenSize; i++) { if(!(tokenData[i] == '-' || (tokenData[i] >= '0' && tokenData[i] <= '9') || (tokenData[i] >= 'A' && tokenData[i] <= 'F') || (tokenData[i] >= 'a' && tokenData[i] <= 'f'))) { return UA_STATUSCODE_BADDECODINGERROR; } } *dst = UA_Guid_fromChars(tokenData); if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(String) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty string? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } /* The actual value is at most of the same length as the source string: * - Shortcut escapes (e.g. "\t") (length 2) are converted to 1 byte * - A single \uXXXX escape (length 6) is converted to at most 3 bytes * - Two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair are * converted to 4 bytes */ char *outputBuffer = (char*)UA_malloc(tokenSize); if(!outputBuffer) return UA_STATUSCODE_BADOUTOFMEMORY; const char *p = (char*)tokenData; const char *end = (char*)&tokenData[tokenSize]; char *pos = outputBuffer; while(p < end) { /* No escaping */ if(*p != '\\') { *(pos++) = *(p++); continue; } /* Escape character */ p++; if(p == end) goto cleanup; if(*p != 'u') { switch(*p) { case '"': case '\\': case '/': *pos = *p; break; case 'b': *pos = '\b'; break; case 'f': *pos = '\f'; break; case 'n': *pos = '\n'; break; case 'r': *pos = '\r'; break; case 't': *pos = '\t'; break; default: goto cleanup; } pos++; p++; continue; } /* Unicode */ if(p + 4 >= end) goto cleanup; int32_t value_signed = decode_unicode_escape(p); if(value_signed < 0) goto cleanup; uint32_t value = (uint32_t)value_signed; p += 5; if(0xD800 <= value && value <= 0xDBFF) { /* Surrogate pair */ if(p + 5 >= end) goto cleanup; if(*p != '\\' || *(p + 1) != 'u') goto cleanup; int32_t value2 = decode_unicode_escape(p + 1); if(value2 < 0xDC00 || value2 > 0xDFFF) goto cleanup; value = ((value - 0xD800u) << 10u) + (uint32_t)((value2 - 0xDC00) + 0x10000); p += 6; } else if(0xDC00 <= value && value <= 0xDFFF) { /* Invalid Unicode '\\u%04X' */ goto cleanup; } size_t length; if(utf8_encode((int32_t)value, pos, &length)) goto cleanup; pos += length; } dst->length = (size_t)(pos - outputBuffer); if(dst->length > 0) { dst->data = (UA_Byte*)outputBuffer; } else { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; UA_free(outputBuffer); } if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; cleanup: UA_free(outputBuffer); return UA_STATUSCODE_BADDECODINGERROR; } DECODE_JSON(ByteString) { ALLOW_NULL; CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* Empty bytestring? */ if(tokenSize == 0) { dst->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL; dst->length = 0; return UA_STATUSCODE_GOOD; } size_t flen = 0; unsigned char* unB64 = UA_unbase64((unsigned char*)tokenData, tokenSize, &flen); if(unB64 == 0) return UA_STATUSCODE_BADDECODINGERROR; dst->data = (u8*)unB64; dst->length = flen; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(LocalizedText) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TEXT, &dst->text, (decodeJsonSignature) String_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } DECODE_JSON(QualifiedName) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[2] = { {UA_JSONKEY_NAME, &dst->name, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_URI, &dst->namespaceIndex, (decodeJsonSignature) UInt16_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, type); } /* Function for searching ahead of the current token. Used for retrieving the * OPC UA type of a token */ static status searchObjectForKeyRec(const char *searchKey, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADNOTFOUND; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first Key*/ for(size_t i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; if(depth == 0) { /* we search only on first layer */ if(jsoneq((char*)ctx->pos, &parseCtx->tokenArray[parseCtx->index], searchKey) == 0) { /*found*/ parseCtx->index++; /*We give back a pointer to the value of the searched key!*/ if (parseCtx->index >= parseCtx->tokenCount) /* We got invalid json. See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=14620 */ return UA_STATUSCODE_BADOUTOFRANGE; *resultIndex = parseCtx->index; return UA_STATUSCODE_GOOD; } } parseCtx->index++; /* value */ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)parseCtx->tokenArray[parseCtx->index].size; parseCtx->index++; /*Object to first element*/ for(size_t i = 0; i < arraySize; i++) { CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { ret = searchObjectForKeyRec(searchKey, ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /* Only Primitive or string */ parseCtx->index++; } } } return ret; } UA_FUNC_ATTR_WARN_UNUSED_RESULT status lookAheadForKey(const char* search, CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; UA_StatusCode ret = searchObjectForKeyRec(search, ctx, parseCtx, resultIndex, depth); parseCtx->index = oldIndex; /* Restore index */ return ret; } /* Function used to jump over an object which cannot be parsed */ static status jumpOverRec(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex, UA_UInt16 depth) { UA_StatusCode ret = UA_STATUSCODE_BADDECODINGERROR; CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first Key*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < objectCount; i++) { CHECK_TOKEN_BOUNDS; parseCtx->index++; /*value*/ CHECK_TOKEN_BOUNDS; if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { size_t arraySize = (size_t)(parseCtx->tokenArray[parseCtx->index].size); parseCtx->index++; /*Object to first element*/ CHECK_TOKEN_BOUNDS; size_t i; for(i = 0; i < arraySize; i++) { if(parseCtx->tokenArray[parseCtx->index].type == JSMN_OBJECT) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else if(parseCtx->tokenArray[parseCtx->index].type == JSMN_ARRAY) { jumpOverRec(ctx, parseCtx, resultIndex, (UA_UInt16)(depth + 1)); } else { /*Only Primitive or string*/ parseCtx->index++; } } } return ret; } static status jumpOverObject(CtxJson *ctx, ParseCtx *parseCtx, size_t *resultIndex) { UA_UInt16 oldIndex = parseCtx->index; /* Save index for later restore */ UA_UInt16 depth = 0; jumpOverRec(ctx, parseCtx, resultIndex, depth); *resultIndex = parseCtx->index; parseCtx->index = oldIndex; /* Restore index */ return UA_STATUSCODE_GOOD; } static status prepareDecodeNodeIdJson(UA_NodeId *dst, CtxJson *ctx, ParseCtx *parseCtx, u8 *fieldCount, DecodeEntry *entries) { /* possible keys: Id, IdType*/ /* Id must always be present */ entries[*fieldCount].fieldName = UA_JSONKEY_ID; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ UA_Boolean hasIdType = false; size_t searchResult = 0; status ret = lookAheadForKey(UA_JSONKEY_IDTYPE, ctx, parseCtx, &searchResult); if(ret == UA_STATUSCODE_GOOD) { /*found*/ hasIdType = true; } if(hasIdType) { size_t size = (size_t)(parseCtx->tokenArray[searchResult].end - parseCtx->tokenArray[searchResult].start); if(size < 1) { return UA_STATUSCODE_BADDECODINGERROR; } char *idType = (char*)(ctx->pos + parseCtx->tokenArray[searchResult].start); if(idType[0] == '2') { dst->identifierType = UA_NODEIDTYPE_GUID; entries[*fieldCount].fieldPointer = &dst->identifier.guid; entries[*fieldCount].function = (decodeJsonSignature) Guid_decodeJson; } else if(idType[0] == '1') { dst->identifierType = UA_NODEIDTYPE_STRING; entries[*fieldCount].fieldPointer = &dst->identifier.string; entries[*fieldCount].function = (decodeJsonSignature) String_decodeJson; } else if(idType[0] == '3') { dst->identifierType = UA_NODEIDTYPE_BYTESTRING; entries[*fieldCount].fieldPointer = &dst->identifier.byteString; entries[*fieldCount].function = (decodeJsonSignature) ByteString_decodeJson; } else { return UA_STATUSCODE_BADDECODINGERROR; } /* Id always present */ (*fieldCount)++; entries[*fieldCount].fieldName = UA_JSONKEY_IDTYPE; entries[*fieldCount].fieldPointer = NULL; entries[*fieldCount].function = NULL; entries[*fieldCount].found = false; entries[*fieldCount].type = NULL; /* IdType */ (*fieldCount)++; } else { dst->identifierType = UA_NODEIDTYPE_NUMERIC; entries[*fieldCount].fieldPointer = &dst->identifier.numeric; entries[*fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[*fieldCount].type = NULL; (*fieldCount)++; } return UA_STATUSCODE_GOOD; } DECODE_JSON(NodeId) { ALLOW_NULL; CHECK_OBJECT; /* NameSpace */ UA_Boolean hasNamespace = false; size_t searchResultNamespace = 0; status ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceIndex = 0; } else { hasNamespace = true; } /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; DecodeEntry entries[3]; ret = prepareDecodeNodeIdJson(dst, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; entries[fieldCount].fieldPointer = &dst->namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->namespaceIndex = 0; } ret = decodeFields(ctx, parseCtx, entries, fieldCount, type); return ret; } DECODE_JSON(ExpandedNodeId) { ALLOW_NULL; CHECK_OBJECT; /* Keep track over number of keys present, incremented if key found */ u8 fieldCount = 0; /* ServerUri */ UA_Boolean hasServerUri = false; size_t searchResultServerUri = 0; status ret = lookAheadForKey(UA_JSONKEY_SERVERURI, ctx, parseCtx, &searchResultServerUri); if(ret != UA_STATUSCODE_GOOD) { dst->serverIndex = 0; } else { hasServerUri = true; } /* NameSpace */ UA_Boolean hasNamespace = false; UA_Boolean isNamespaceString = false; size_t searchResultNamespace = 0; ret = lookAheadForKey(UA_JSONKEY_NAMESPACE, ctx, parseCtx, &searchResultNamespace); if(ret != UA_STATUSCODE_GOOD) { dst->namespaceUri = UA_STRING_NULL; } else { hasNamespace = true; jsmntok_t nsToken = parseCtx->tokenArray[searchResultNamespace]; if(nsToken.type == JSMN_STRING) isNamespaceString = true; } DecodeEntry entries[4]; ret = prepareDecodeNodeIdJson(&dst->nodeId, ctx, parseCtx, &fieldCount, entries); if(ret != UA_STATUSCODE_GOOD) return ret; if(hasNamespace) { entries[fieldCount].fieldName = UA_JSONKEY_NAMESPACE; if(isNamespaceString) { entries[fieldCount].fieldPointer = &dst->namespaceUri; entries[fieldCount].function = (decodeJsonSignature) String_decodeJson; } else { entries[fieldCount].fieldPointer = &dst->nodeId.namespaceIndex; entries[fieldCount].function = (decodeJsonSignature) UInt16_decodeJson; } entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } if(hasServerUri) { entries[fieldCount].fieldName = UA_JSONKEY_SERVERURI; entries[fieldCount].fieldPointer = &dst->serverIndex; entries[fieldCount].function = (decodeJsonSignature) UInt32_decodeJson; entries[fieldCount].found = false; entries[fieldCount].type = NULL; fieldCount++; } else { dst->serverIndex = 0; } return decodeFields(ctx, parseCtx, entries, fieldCount, type); } DECODE_JSON(DateTime) { CHECK_STRING; CHECK_TOKEN_BOUNDS; size_t tokenSize; char* tokenData; GET_TOKEN(tokenData, tokenSize); /* TODO: proper ISO 8601:2004 parsing, musl strptime!*/ /* DateTime ISO 8601:2004 without milli is 20 Characters, with millis 24 */ if(tokenSize != 20 && tokenSize != 24) { return UA_STATUSCODE_BADDECODINGERROR; } /* sanity check */ if(tokenData[4] != '-' || tokenData[7] != '-' || tokenData[10] != 'T' || tokenData[13] != ':' || tokenData[16] != ':' || !(tokenData[19] == 'Z' || tokenData[19] == '.')) { return UA_STATUSCODE_BADDECODINGERROR; } struct mytm dts; memset(&dts, 0, sizeof(dts)); UA_UInt64 year = 0; atoiUnsigned(&tokenData[0], 4, &year); dts.tm_year = (UA_UInt16)year - 1900; UA_UInt64 month = 0; atoiUnsigned(&tokenData[5], 2, &month); dts.tm_mon = (UA_UInt16)month - 1; UA_UInt64 day = 0; atoiUnsigned(&tokenData[8], 2, &day); dts.tm_mday = (UA_UInt16)day; UA_UInt64 hour = 0; atoiUnsigned(&tokenData[11], 2, &hour); dts.tm_hour = (UA_UInt16)hour; UA_UInt64 min = 0; atoiUnsigned(&tokenData[14], 2, &min); dts.tm_min = (UA_UInt16)min; UA_UInt64 sec = 0; atoiUnsigned(&tokenData[17], 2, &sec); dts.tm_sec = (UA_UInt16)sec; UA_UInt64 msec = 0; if(tokenSize == 24) { atoiUnsigned(&tokenData[20], 3, &msec); } long long sinceunix = __tm_to_secs(&dts); UA_DateTime dt = (UA_DateTime)((UA_UInt64)(sinceunix*UA_DATETIME_SEC + UA_DATETIME_UNIX_EPOCH) + (UA_UInt64)(UA_DATETIME_MSEC * msec)); *dst = dt; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } DECODE_JSON(StatusCode) { status ret = DECODE_DIRECT_JSON(dst, UInt32); if(ret != UA_STATUSCODE_GOOD) return ret; if(moveToken) parseCtx->index++; return UA_STATUSCODE_GOOD; } static status VariantDimension_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type; const UA_DataType *dimType = &UA_TYPES[UA_TYPES_UINT32]; return Array_decodeJson_internal((void**)dst, dimType, ctx, parseCtx, moveToken); } DECODE_JSON(Variant) { ALLOW_NULL; CHECK_OBJECT; /* First search for the variant type in the json object. */ size_t searchResultType = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPE, ctx, parseCtx, &searchResultType); if(ret != UA_STATUSCODE_GOOD) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } size_t size = ((size_t)parseCtx->tokenArray[searchResultType].end - (size_t)parseCtx->tokenArray[searchResultType].start); /* check if size is zero or the type is not a number */ if(size < 1 || parseCtx->tokenArray[searchResultType].type != JSMN_PRIMITIVE) return UA_STATUSCODE_BADDECODINGERROR; /* Parse the type */ UA_UInt64 idTypeDecoded = 0; char *idTypeEncoded = (char*)(ctx->pos + parseCtx->tokenArray[searchResultType].start); status typeDecodeStatus = atoiUnsigned(idTypeEncoded, size, &idTypeDecoded); if(typeDecodeStatus != UA_STATUSCODE_GOOD) return typeDecodeStatus; /* A NULL Variant */ if(idTypeDecoded == 0) { skipObject(parseCtx); return UA_STATUSCODE_GOOD; } /* Set the type */ UA_NodeId typeNodeId = UA_NODEID_NUMERIC(0, (UA_UInt32)idTypeDecoded); dst->type = UA_findDataType(&typeNodeId); if(!dst->type) return UA_STATUSCODE_BADDECODINGERROR; /* Search for body */ size_t searchResultBody = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchResultBody); if(ret != UA_STATUSCODE_GOOD) { /*TODO: no body? set value NULL?*/ return UA_STATUSCODE_BADDECODINGERROR; } /* value is an array? */ UA_Boolean isArray = false; if(parseCtx->tokenArray[searchResultBody].type == JSMN_ARRAY) { isArray = true; dst->arrayLength = (size_t)parseCtx->tokenArray[searchResultBody].size; } /* Has the variant dimension? */ UA_Boolean hasDimension = false; size_t searchResultDim = 0; ret = lookAheadForKey(UA_JSONKEY_DIMENSION, ctx, parseCtx, &searchResultDim); if(ret == UA_STATUSCODE_GOOD) { hasDimension = true; dst->arrayDimensionsSize = (size_t)parseCtx->tokenArray[searchResultDim].size; } /* no array but has dimension. error? */ if(!isArray && hasDimension) return UA_STATUSCODE_BADDECODINGERROR; /* Get the datatype of the content. The type must be a builtin data type. * All not-builtin types are wrapped in an ExtensionObject. */ if(dst->type->typeKind > UA_TYPES_DIAGNOSTICINFO) return UA_STATUSCODE_BADDECODINGERROR; /* A variant cannot contain a variant. But it can contain an array of * variants */ if(dst->type->typeKind == UA_DATATYPEKIND_VARIANT && !isArray) return UA_STATUSCODE_BADDECODINGERROR; /* Decode an array */ if(isArray) { DecodeEntry entries[3] = { {UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, &dst->data, (decodeJsonSignature) Array_decodeJson, false, NULL}, {UA_JSONKEY_DIMENSION, &dst->arrayDimensions, (decodeJsonSignature) VariantDimension_decodeJson, false, NULL}}; if(!hasDimension) { ret = decodeFields(ctx, parseCtx, entries, 2, dst->type); /*use first 2 fields*/ } else { ret = decodeFields(ctx, parseCtx, entries, 3, dst->type); /*use all fields*/ } return ret; } /* Decode a value wrapped in an ExtensionObject */ if(dst->type->typeKind == UA_DATATYPEKIND_EXTENSIONOBJECT) { DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst, (decodeJsonSignature)Variant_decodeJsonUnwrapExtensionObject, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } /* Allocate Memory for Body */ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; DecodeEntry entries[2] = {{UA_JSONKEY_TYPE, NULL, NULL, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonInternal, false, NULL}}; return decodeFields(ctx, parseCtx, entries, 2, dst->type); } DECODE_JSON(DataValue) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[6] = { {UA_JSONKEY_VALUE, &dst->value, (decodeJsonSignature) Variant_decodeJson, false, NULL}, {UA_JSONKEY_STATUS, &dst->status, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_SOURCETIMESTAMP, &dst->sourceTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SOURCEPICOSECONDS, &dst->sourcePicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_SERVERTIMESTAMP, &dst->serverTimestamp, (decodeJsonSignature) DateTime_decodeJson, false, NULL}, {UA_JSONKEY_SERVERPICOSECONDS, &dst->serverPicoseconds, (decodeJsonSignature) UInt16_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 6, type); dst->hasValue = entries[0].found; dst->hasStatus = entries[1].found; dst->hasSourceTimestamp = entries[2].found; dst->hasSourcePicoseconds = entries[3].found; dst->hasServerTimestamp = entries[4].found; dst->hasServerPicoseconds = entries[5].found; return ret; } DECODE_JSON(ExtensionObject) { ALLOW_NULL; CHECK_OBJECT; /* Search for Encoding */ size_t searchEncodingResult = 0; status ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); /* If no encoding found it is structure encoding */ if(ret != UA_STATUSCODE_GOOD) { UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /* TYPEID not found, abort */ return UA_STATUSCODE_BADENCODINGERROR; } /* parse the nodeid */ /*for restore*/ UA_UInt16 index = parseCtx->index; parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) return ret; /*restore*/ parseCtx->index = index; const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(!typeOfBody) { /*dont decode body: 1. save as bytestring, 2. jump over*/ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_NodeId_copy(&typeId, &dst->content.encoded.typeId); /*Check if Object in Extentionobject*/ if(getJsmnType(parseCtx) != JSMN_OBJECT) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /*Search for Body to save*/ size_t searchBodyResult = 0; ret = lookAheadForKey(UA_JSONKEY_BODY, ctx, parseCtx, &searchBodyResult); if(ret != UA_STATUSCODE_GOOD) { /*No Body*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } if(searchBodyResult >= (size_t)parseCtx->tokenCount) { /*index not in Tokenarray*/ UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Get the size of the Object as a string, not the Object key count! */ UA_Int64 sizeOfJsonString =(parseCtx->tokenArray[searchBodyResult].end - parseCtx->tokenArray[searchBodyResult].start); char* bodyJsonString = (char*)(ctx->pos + parseCtx->tokenArray[searchBodyResult].start); if(sizeOfJsonString <= 0) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADDECODINGERROR; } /* Save encoded as bytestring. */ ret = UA_ByteString_allocBuffer(&dst->content.encoded.body, (size_t)sizeOfJsonString); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } memcpy(dst->content.encoded.body.data, bodyJsonString, (size_t)sizeOfJsonString); size_t tokenAfteExtensionObject = 0; jumpOverObject(ctx, parseCtx, &tokenAfteExtensionObject); if(tokenAfteExtensionObject == 0) { /*next object token not found*/ UA_NodeId_deleteMembers(&typeId); UA_ByteString_deleteMembers(&dst->content.encoded.body); return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index = (UA_UInt16)tokenAfteExtensionObject; return UA_STATUSCODE_GOOD; } /*Type id not used anymore, typeOfBody has type*/ UA_NodeId_deleteMembers(&typeId); /*Set Found Type*/ dst->content.decoded.type = typeOfBody; dst->encoding = UA_EXTENSIONOBJECT_DECODED; if(searchTypeIdResult != 0) { dst->content.decoded.data = UA_new(typeOfBody); if(!dst->content.decoded.data) return UA_STATUSCODE_BADOUTOFMEMORY; UA_NodeId typeId_dummy; DecodeEntry entries[2] = { {UA_JSONKEY_TYPEID, &typeId_dummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->content.decoded.data, (decodeJsonSignature) decodeJsonJumpTable[typeOfBody->typeKind], false, NULL} }; return decodeFields(ctx, parseCtx, entries, 2, typeOfBody); } else { return UA_STATUSCODE_BADDECODINGERROR; } } else { /* UA_JSONKEY_ENCODING found */ /*Parse the encoding*/ UA_UInt64 encoding = 0; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); if(encoding == 1) { /* BYTESTRING in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else if(encoding == 2) { /* XmlElement in Json Body */ dst->encoding = UA_EXTENSIONOBJECT_ENCODED_XML; UA_UInt16 encodingTypeJson; DecodeEntry entries[3] = { {UA_JSONKEY_ENCODING, &encodingTypeJson, (decodeJsonSignature) UInt16_decodeJson, false, NULL}, {UA_JSONKEY_BODY, &dst->content.encoded.body, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_TYPEID, &dst->content.encoded.typeId, (decodeJsonSignature) NodeId_decodeJson, false, NULL} }; return decodeFields(ctx, parseCtx, entries, 3, type); } else { return UA_STATUSCODE_BADDECODINGERROR; } } return UA_STATUSCODE_BADNOTIMPLEMENTED; } static status Variant_decodeJsonUnwrapExtensionObject(UA_Variant *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) type, (void) moveToken; /*EXTENSIONOBJECT POSITION!*/ UA_UInt16 old_index = parseCtx->index; UA_Boolean typeIdFound; /* Decode the DataType */ UA_NodeId typeId; UA_NodeId_init(&typeId); size_t searchTypeIdResult = 0; status ret = lookAheadForKey(UA_JSONKEY_TYPEID, ctx, parseCtx, &searchTypeIdResult); if(ret != UA_STATUSCODE_GOOD) { /*No Typeid found*/ typeIdFound = false; /*return UA_STATUSCODE_BADDECODINGERROR;*/ } else { typeIdFound = true; /* parse the nodeid */ parseCtx->index = (UA_UInt16)searchTypeIdResult; ret = NodeId_decodeJson(&typeId, &UA_TYPES[UA_TYPES_NODEID], ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_NodeId_deleteMembers(&typeId); return ret; } /*restore index, ExtensionObject position*/ parseCtx->index = old_index; } /* ---Decode the EncodingByte--- */ if(!typeIdFound) return UA_STATUSCODE_BADDECODINGERROR; UA_Boolean encodingFound = false; /*Search for Encoding*/ size_t searchEncodingResult = 0; ret = lookAheadForKey(UA_JSONKEY_ENCODING, ctx, parseCtx, &searchEncodingResult); UA_UInt64 encoding = 0; /*If no encoding found it is Structure encoding*/ if(ret == UA_STATUSCODE_GOOD) { /*FOUND*/ encodingFound = true; char *extObjEncoding = (char*)(ctx->pos + parseCtx->tokenArray[searchEncodingResult].start); size_t size = (size_t)(parseCtx->tokenArray[searchEncodingResult].end - parseCtx->tokenArray[searchEncodingResult].start); atoiUnsigned(extObjEncoding, size, &encoding); } const UA_DataType *typeOfBody = UA_findDataType(&typeId); if(encoding == 0 || typeOfBody != NULL) { /*This value is 0 if the body is Structure encoded as a JSON object (see 5.4.6).*/ /* Found a valid type and it is structure encoded so it can be unwrapped */ if (typeOfBody == NULL) return UA_STATUSCODE_BADDECODINGERROR; dst->type = typeOfBody; /* Allocate memory for type*/ dst->data = UA_new(dst->type); if(!dst->data) { UA_NodeId_deleteMembers(&typeId); return UA_STATUSCODE_BADOUTOFMEMORY; } /* Decode the content */ UA_NodeId nodeIddummy; DecodeEntry entries[3] = { {UA_JSONKEY_TYPEID, &nodeIddummy, (decodeJsonSignature) NodeId_decodeJson, false, NULL}, {UA_JSONKEY_BODY, dst->data, (decodeJsonSignature) decodeJsonJumpTable[dst->type->typeKind], false, NULL}, {UA_JSONKEY_ENCODING, NULL, NULL, false, NULL}}; ret = decodeFields(ctx, parseCtx, entries, encodingFound ? 3:2, typeOfBody); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else if(encoding == 1 || encoding == 2 || typeOfBody == NULL) { UA_NodeId_deleteMembers(&typeId); /* decode as ExtensionObject */ dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]; /* Allocate memory for extensionobject*/ dst->data = UA_new(dst->type); if(!dst->data) return UA_STATUSCODE_BADOUTOFMEMORY; /* decode: Does not move tokenindex. */ ret = DECODE_DIRECT_JSON(dst->data, ExtensionObject); if(ret != UA_STATUSCODE_GOOD) { UA_free(dst->data); dst->data = NULL; } } else { /*no recognized encoding type*/ return UA_STATUSCODE_BADDECODINGERROR; } return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken); DECODE_JSON(DiagnosticInfo) { ALLOW_NULL; CHECK_OBJECT; DecodeEntry entries[7] = { {UA_JSONKEY_SYMBOLICID, &dst->symbolicId, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_NAMESPACEURI, &dst->namespaceUri, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALIZEDTEXT, &dst->localizedText, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_LOCALE, &dst->locale, (decodeJsonSignature) Int32_decodeJson, false, NULL}, {UA_JSONKEY_ADDITIONALINFO, &dst->additionalInfo, (decodeJsonSignature) String_decodeJson, false, NULL}, {UA_JSONKEY_INNERSTATUSCODE, &dst->innerStatusCode, (decodeJsonSignature) StatusCode_decodeJson, false, NULL}, {UA_JSONKEY_INNERDIAGNOSTICINFO, &dst->innerDiagnosticInfo, (decodeJsonSignature) DiagnosticInfoInner_decodeJson, false, NULL}}; status ret = decodeFields(ctx, parseCtx, entries, 7, type); dst->hasSymbolicId = entries[0].found; dst->hasNamespaceUri = entries[1].found; dst->hasLocalizedText = entries[2].found; dst->hasLocale = entries[3].found; dst->hasAdditionalInfo = entries[4].found; dst->hasInnerStatusCode = entries[5].found; dst->hasInnerDiagnosticInfo = entries[6].found; return ret; } status DiagnosticInfoInner_decodeJson(void* dst, const UA_DataType* type, CtxJson* ctx, ParseCtx* parseCtx, UA_Boolean moveToken) { UA_DiagnosticInfo *inner = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo)); if(inner == NULL) { return UA_STATUSCODE_BADOUTOFMEMORY; } memcpy(dst, &inner, sizeof(UA_DiagnosticInfo*)); /* Copy new Pointer do dest */ return DiagnosticInfo_decodeJson(inner, type, ctx, parseCtx, moveToken); } status decodeFields(CtxJson *ctx, ParseCtx *parseCtx, DecodeEntry *entries, size_t entryCount, const UA_DataType *type) { CHECK_TOKEN_BOUNDS; size_t objectCount = (size_t)(parseCtx->tokenArray[parseCtx->index].size); status ret = UA_STATUSCODE_GOOD; if(entryCount == 1) { if(*(entries[0].fieldName) == 0) { /*No MemberName*/ return entries[0].function(entries[0].fieldPointer, type, ctx, parseCtx, true); /*ENCODE DIRECT*/ } } else if(entryCount == 0) { return UA_STATUSCODE_BADDECODINGERROR; } parseCtx->index++; /*go to first key*/ CHECK_TOKEN_BOUNDS; for (size_t currentObjectCount = 0; currentObjectCount < objectCount && parseCtx->index < parseCtx->tokenCount; currentObjectCount++) { /* start searching at the index of currentObjectCount */ for (size_t i = currentObjectCount; i < entryCount + currentObjectCount; i++) { /* Search for KEY, if found outer loop will be one less. Best case * is objectCount if in order! */ size_t index = i % entryCount; CHECK_TOKEN_BOUNDS; if(jsoneq((char*) ctx->pos, &parseCtx->tokenArray[parseCtx->index], entries[index].fieldName) != 0) continue; if(entries[index].found) { /*Duplicate Key found, abort.*/ return UA_STATUSCODE_BADDECODINGERROR; } entries[index].found = true; parseCtx->index++; /*goto value*/ CHECK_TOKEN_BOUNDS; /* Find the data type. * TODO: get rid of parameter type. Only forward via DecodeEntry. */ const UA_DataType *membertype = type; if(entries[index].type) membertype = entries[index].type; if(entries[index].function != NULL) { ret = entries[index].function(entries[index].fieldPointer, membertype, ctx, parseCtx, true); /*Move Token True*/ if(ret != UA_STATUSCODE_GOOD) return ret; } else { /*overstep single value, this will not work if object or array Only used not to double parse pre looked up type, but it has to be overstepped*/ parseCtx->index++; } break; } } return ret; } static status Array_decodeJson_internal(void **dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; status ret; if(parseCtx->tokenArray[parseCtx->index].type != JSMN_ARRAY) return UA_STATUSCODE_BADDECODINGERROR; size_t length = (size_t)parseCtx->tokenArray[parseCtx->index].size; /* Save the length of the array */ size_t *p = (size_t*) dst - 1; *p = length; /* Return early for empty arrays */ if(length == 0) { *dst = UA_EMPTY_ARRAY_SENTINEL; return UA_STATUSCODE_GOOD; } /* Allocate memory */ *dst = UA_calloc(length, type->memSize); if(*dst == NULL) return UA_STATUSCODE_BADOUTOFMEMORY; parseCtx->index++; /* We go to first Array member!*/ /* Decode array members */ uintptr_t ptr = (uintptr_t)*dst; for(size_t i = 0; i < length; ++i) { ret = decodeJsonJumpTable[type->typeKind]((void*)ptr, type, ctx, parseCtx, true); if(ret != UA_STATUSCODE_GOOD) { UA_Array_delete(*dst, i+1, type); *dst = NULL; return ret; } ptr += type->memSize; } return UA_STATUSCODE_GOOD; } /*Wrapper for array with valid decodingStructure.*/ static status Array_decodeJson(void * dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return Array_decodeJson_internal((void **)dst, type, ctx, parseCtx, moveToken); } static status decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } static status decodeJsonNotImplemented(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void)dst, (void)type, (void)ctx, (void)parseCtx, (void)moveToken; return UA_STATUSCODE_BADNOTIMPLEMENTED; } const decodeJsonSignature decodeJsonJumpTable[UA_DATATYPEKINDS] = { (decodeJsonSignature)Boolean_decodeJson, (decodeJsonSignature)SByte_decodeJson, /* SByte */ (decodeJsonSignature)Byte_decodeJson, (decodeJsonSignature)Int16_decodeJson, /* Int16 */ (decodeJsonSignature)UInt16_decodeJson, (decodeJsonSignature)Int32_decodeJson, /* Int32 */ (decodeJsonSignature)UInt32_decodeJson, (decodeJsonSignature)Int64_decodeJson, /* Int64 */ (decodeJsonSignature)UInt64_decodeJson, (decodeJsonSignature)Float_decodeJson, (decodeJsonSignature)Double_decodeJson, (decodeJsonSignature)String_decodeJson, (decodeJsonSignature)DateTime_decodeJson, /* DateTime */ (decodeJsonSignature)Guid_decodeJson, (decodeJsonSignature)ByteString_decodeJson, /* ByteString */ (decodeJsonSignature)String_decodeJson, /* XmlElement */ (decodeJsonSignature)NodeId_decodeJson, (decodeJsonSignature)ExpandedNodeId_decodeJson, (decodeJsonSignature)StatusCode_decodeJson, /* StatusCode */ (decodeJsonSignature)QualifiedName_decodeJson, /* QualifiedName */ (decodeJsonSignature)LocalizedText_decodeJson, (decodeJsonSignature)ExtensionObject_decodeJson, (decodeJsonSignature)DataValue_decodeJson, (decodeJsonSignature)Variant_decodeJson, (decodeJsonSignature)DiagnosticInfo_decodeJson, (decodeJsonSignature)decodeJsonNotImplemented, /* Decimal */ (decodeJsonSignature)Int32_decodeJson, /* Enum */ (decodeJsonSignature)decodeJsonStructure, (decodeJsonSignature)decodeJsonNotImplemented, /* Structure with optional fields */ (decodeJsonSignature)decodeJsonNotImplemented, /* Union */ (decodeJsonSignature)decodeJsonNotImplemented /* BitfieldCluster */ }; decodeJsonSignature getDecodeSignature(u8 index) { return decodeJsonJumpTable[index]; } status tokenize(ParseCtx *parseCtx, CtxJson *ctx, const UA_ByteString *src) { /* Set up the context */ ctx->pos = &src->data[0]; ctx->end = &src->data[src->length]; ctx->depth = 0; parseCtx->tokenCount = 0; parseCtx->index = 0; /*Set up tokenizer jsmn*/ jsmn_parser p; jsmn_init(&p); parseCtx->tokenCount = (UA_Int32) jsmn_parse(&p, (char*)src->data, src->length, parseCtx->tokenArray, UA_JSON_MAXTOKENCOUNT); if(parseCtx->tokenCount < 0) { if(parseCtx->tokenCount == JSMN_ERROR_NOMEM) return UA_STATUSCODE_BADOUTOFMEMORY; return UA_STATUSCODE_BADDECODINGERROR; } return UA_STATUSCODE_GOOD; } UA_StatusCode decodeJsonInternal(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { return decodeJsonJumpTable[type->typeKind](dst, type, ctx, parseCtx, moveToken); } status UA_FUNC_ATTR_WARN_UNUSED_RESULT UA_decodeJson(const UA_ByteString *src, void *dst, const UA_DataType *type) { #ifndef UA_ENABLE_TYPEDESCRIPTION return UA_STATUSCODE_BADNOTSUPPORTED; #endif if(dst == NULL || src == NULL || type == NULL) { return UA_STATUSCODE_BADARGUMENTSMISSING; } /* Set up the context */ CtxJson ctx; ParseCtx parseCtx; parseCtx.tokenArray = (jsmntok_t*)UA_malloc(sizeof(jsmntok_t) * UA_JSON_MAXTOKENCOUNT); if(!parseCtx.tokenArray) return UA_STATUSCODE_BADOUTOFMEMORY; status ret = tokenize(&parseCtx, &ctx, src); if(ret != UA_STATUSCODE_GOOD) goto cleanup; /* Assume the top-level element is an object */ if(parseCtx.tokenCount < 1 || parseCtx.tokenArray[0].type != JSMN_OBJECT) { if(parseCtx.tokenCount == 1) { if(parseCtx.tokenArray[0].type == JSMN_PRIMITIVE || parseCtx.tokenArray[0].type == JSMN_STRING) { /* Only a primitive to parse. Do it directly. */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); goto cleanup; } } ret = UA_STATUSCODE_BADDECODINGERROR; goto cleanup; } /* Decode */ memset(dst, 0, type->memSize); /* Initialize the value */ ret = decodeJsonJumpTable[type->typeKind](dst, type, &ctx, &parseCtx, true); cleanup: UA_free(parseCtx.tokenArray); /* sanity check if all Tokens were processed */ if(!(parseCtx.index == parseCtx.tokenCount || parseCtx.index == parseCtx.tokenCount-1)) { ret = UA_STATUSCODE_BADDECODINGERROR; } if(ret != UA_STATUSCODE_GOOD) UA_deleteMembers(dst, type); /* Clean up */ return ret; }
encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; }
encodeJsonStructure(const void *src, const UA_DataType *type, CtxJson *ctx) { /* Check the recursion limit */ if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; status ret = writeJsonObjStart(ctx); uintptr_t ptr = (uintptr_t) src; u8 membersSize = type->membersSize; const UA_DataType * typelists[2] = {UA_TYPES, &type[-type->typeIndex]}; for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; if(m->memberName != NULL && *m->memberName != 0) ret |= writeJsonKey(ctx, m->memberName); if(!m->isArray) { ptr += m->padding; size_t memSize = mt->memSize; ret |= encodeJsonJumpTable[mt->typeKind]((const void*) ptr, mt, ctx); ptr += memSize; } else { ptr += m->padding; const size_t length = *((const size_t*) ptr); ptr += sizeof (size_t); ret |= encodeJsonArray(ctx, *(void * const *)ptr, length, mt); ptr += sizeof (void*); } } ret |= writeJsonObjEnd(ctx); ctx->depth--; return ret; }
{'added': [(111, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (112, ' return UA_STATUSCODE_BADENCODINGERROR;'), (126, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (127, ' return UA_STATUSCODE_BADENCODINGERROR;'), (128, ' ctx->depth++;'), (129, ' ctx->commaNeeded[ctx->depth] = false;'), (1132, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (1390, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)'), (3161, ' if(ctx->depth >= UA_JSON_ENCODING_MAX_RECURSION)')], 'deleted': [(124, ' ctx->commaNeeded[++ctx->depth] = false;'), (1127, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (1385, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)'), (3156, ' if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION)')]}
9
4
2,401
17,444
https://github.com/open62541/open62541
CVE-2020-36429
['CWE-787']
memcached.c
get_conn_text
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * memcached - memory caching daemon * * https://www.memcached.org/ * * Copyright 2003 Danga Interactive, Inc. All rights reserved. * * Use and distribution licensed under the BSD license. See * the LICENSE file for full text. * * Authors: * Anatoly Vorobey <mellon@pobox.com> * Brad Fitzpatrick <brad@danga.com> */ #include "memcached.h" #ifdef EXTSTORE #include "storage.h" #endif #include "authfile.h" #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/uio.h> #include <ctype.h> #include <stdarg.h> /* some POSIX systems need the following definition * to get mlockall flags out of sys/mman.h. */ #ifndef _P1003_1B_VISIBLE #define _P1003_1B_VISIBLE #endif /* need this to get IOV_MAX on some platforms. */ #ifndef __need_IOV_MAX #define __need_IOV_MAX #endif #include <pwd.h> #include <sys/mman.h> #include <fcntl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <assert.h> #include <limits.h> #include <sysexits.h> #include <stddef.h> #ifdef HAVE_GETOPT_LONG #include <getopt.h> #endif #ifdef TLS #include "tls.h" #endif #if defined(__FreeBSD__) #include <sys/sysctl.h> #endif /* FreeBSD 4.x doesn't have IOV_MAX exposed. */ #ifndef IOV_MAX #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__) # define IOV_MAX 1024 /* GNU/Hurd don't set MAXPATHLEN * http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */ #ifndef MAXPATHLEN #define MAXPATHLEN 4096 #endif #endif #endif /* * forward declarations */ static void drive_machine(conn *c); static int new_socket(struct addrinfo *ai); static ssize_t tcp_read(conn *arg, void *buf, size_t count); static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags); static ssize_t tcp_write(conn *arg, void *buf, size_t count); enum try_read_result { READ_DATA_RECEIVED, READ_NO_DATA_RECEIVED, READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */ READ_MEMORY_ERROR /** failed to allocate more memory */ }; static int try_read_command_negotiate(conn *c); static int try_read_command_udp(conn *c); static int try_read_command_binary(conn *c); static int try_read_command_ascii(conn *c); static int try_read_command_asciiauth(conn *c); static enum try_read_result try_read_network(conn *c); static enum try_read_result try_read_udp(conn *c); static void conn_set_state(conn *c, enum conn_states state); static int start_conn_timeout_thread(); /* stats */ static void stats_init(void); static void server_stats(ADD_STAT add_stats, conn *c); static void process_stat_settings(ADD_STAT add_stats, void *c); static void conn_to_str(const conn *c, char *addr, char *svr_addr); /** Return a datum for stats in binary protocol */ static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c); /* defaults */ static void settings_init(void); /* event handling, network IO */ static void event_handler(const int fd, const short which, void *arg); static void conn_close(conn *c); static void conn_init(void); static bool update_event(conn *c, const int new_flags); static void complete_nread(conn *c); static void process_command(conn *c, char *command); static void write_and_free(conn *c, char *buf, int bytes); static int ensure_iov_space(conn *c); static int add_iov(conn *c, const void *buf, int len); static int add_chunked_item_iovs(conn *c, item *it, int len); static int add_msghdr(conn *c); static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow); static void write_bin_miss_response(conn *c, char *key, size_t nkey); #ifdef EXTSTORE static void _get_extstore_cb(void *e, obj_io *io, int ret); static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt); #endif static void conn_free(conn *c); /** exported globals **/ struct stats stats; struct stats_state stats_state; struct settings settings; time_t process_started; /* when the process was started */ conn **conns; struct slab_rebalance slab_rebal; volatile int slab_rebalance_signal; #ifdef EXTSTORE /* hoping this is temporary; I'd prefer to cut globals, but will complete this * battle another day. */ void *ext_storage; #endif /** file scope variables **/ static conn *listen_conn = NULL; static int max_fds; static struct event_base *main_base; enum transmit_result { TRANSMIT_COMPLETE, /** All done writing. */ TRANSMIT_INCOMPLETE, /** More data remaining to write. */ TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */ TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */ }; /* Default methods to read from/ write to a socket */ ssize_t tcp_read(conn *c, void *buf, size_t count) { assert (c != NULL); return read(c->sfd, buf, count); } ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) { assert (c != NULL); return sendmsg(c->sfd, msg, flags); } ssize_t tcp_write(conn *c, void *buf, size_t count) { assert (c != NULL); return write(c->sfd, buf, count); } static enum transmit_result transmit(conn *c); /* This reduces the latency without adding lots of extra wiring to be able to * notify the listener thread of when to listen again. * Also, the clock timer could be broken out into its own thread and we * can block the listener via a condition. */ static volatile bool allow_new_conns = true; static struct event maxconnsevent; static void maxconns_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 0, .tv_usec = 10000}; if (fd == -42 || allow_new_conns == false) { /* reschedule in 10ms if we need to keep polling */ evtimer_set(&maxconnsevent, maxconns_handler, 0); event_base_set(main_base, &maxconnsevent); evtimer_add(&maxconnsevent, &t); } else { evtimer_del(&maxconnsevent); accept_new_conns(true); } } #define REALTIME_MAXDELTA 60*60*24*30 /* * given time value that's either unix time or delta from current unix time, return * unix time. Use the fact that delta can't exceed one month (and real time value can't * be that low). */ static rel_time_t realtime(const time_t exptime) { /* no. of seconds in 30 days - largest possible delta exptime */ if (exptime == 0) return 0; /* 0 means never expire */ if (exptime > REALTIME_MAXDELTA) { /* if item expiration is at/before the server started, give it an expiration time of 1 second after the server started. (because 0 means don't expire). without this, we'd underflow and wrap around to some large value way in the future, effectively making items expiring in the past really expiring never */ if (exptime <= process_started) return (rel_time_t)1; return (rel_time_t)(exptime - process_started); } else { return (rel_time_t)(exptime + current_time); } } static void stats_init(void) { memset(&stats, 0, sizeof(struct stats)); memset(&stats_state, 0, sizeof(struct stats_state)); stats_state.accepting_conns = true; /* assuming we start in this state. */ /* make the time we started always be 2 seconds before we really did, so time(0) - time.started is never zero. if so, things like 'settings.oldest_live' which act as booleans as well as values are now false in boolean context... */ process_started = time(0) - ITEM_UPDATE_INTERVAL - 2; stats_prefix_init(); } static void stats_reset(void) { STATS_LOCK(); memset(&stats, 0, sizeof(struct stats)); stats_prefix_clear(); STATS_UNLOCK(); threadlocal_stats_reset(); item_stats_reset(); } static void settings_init(void) { settings.use_cas = true; settings.access = 0700; settings.port = 11211; settings.udpport = 0; #ifdef TLS settings.ssl_enabled = false; settings.ssl_ctx = NULL; settings.ssl_chain_cert = NULL; settings.ssl_key = NULL; settings.ssl_verify_mode = SSL_VERIFY_NONE; settings.ssl_keyformat = SSL_FILETYPE_PEM; settings.ssl_ciphers = NULL; settings.ssl_ca_cert = NULL; settings.ssl_last_cert_refresh_time = current_time; settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB) #endif /* By default this string should be NULL for getaddrinfo() */ settings.inter = NULL; settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */ settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */ settings.verbose = 0; settings.oldest_live = 0; settings.oldest_cas = 0; /* supplements accuracy of oldest_live */ settings.evict_to_free = 1; /* push old items out of cache when memory runs out */ settings.socketpath = NULL; /* by default, not using a unix socket */ settings.auth_file = NULL; /* by default, not using ASCII authentication tokens */ settings.factor = 1.25; settings.chunk_size = 48; /* space for a modest key and value */ settings.num_threads = 4; /* N workers */ settings.num_threads_per_udp = 0; settings.prefix_delimiter = ':'; settings.detail_enabled = 0; settings.reqs_per_event = 20; settings.backlog = 1024; settings.binding_protocol = negotiating_prot; settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */ settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */ settings.slab_chunk_size_max = settings.slab_page_size / 2; settings.sasl = false; settings.maxconns_fast = true; settings.lru_crawler = false; settings.lru_crawler_sleep = 100; settings.lru_crawler_tocrawl = 0; settings.lru_maintainer_thread = false; settings.lru_segmented = true; settings.hot_lru_pct = 20; settings.warm_lru_pct = 40; settings.hot_max_factor = 0.2; settings.warm_max_factor = 2.0; settings.temp_lru = false; settings.temporary_ttl = 61; settings.idle_timeout = 0; /* disabled */ settings.hashpower_init = 0; settings.slab_reassign = true; settings.slab_automove = 1; settings.slab_automove_ratio = 0.8; settings.slab_automove_window = 30; settings.shutdown_command = false; settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT; settings.flush_enabled = true; settings.dump_enabled = true; settings.crawls_persleep = 1000; settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE; settings.logger_buf_size = LOGGER_BUF_SIZE; settings.drop_privileges = false; #ifdef MEMCACHED_DEBUG settings.relaxed_privileges = false; #endif } /* * Adds a message header to a connection. * * Returns 0 on success, -1 on out-of-memory. */ static int add_msghdr(conn *c) { struct msghdr *msg; assert(c != NULL); if (c->msgsize == c->msgused) { msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr)); if (! msg) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->msglist = msg; c->msgsize *= 2; } msg = c->msglist + c->msgused; /* this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the last 3 of which aren't defined on solaris: */ memset(msg, 0, sizeof(struct msghdr)); msg->msg_iov = &c->iov[c->iovused]; if (IS_UDP(c->transport) && c->request_addr_size > 0) { msg->msg_name = &c->request_addr; msg->msg_namelen = c->request_addr_size; } c->msgbytes = 0; c->msgused++; if (IS_UDP(c->transport)) { /* Leave room for the UDP header, which we'll fill in later. */ return add_iov(c, NULL, UDP_HEADER_SIZE); } return 0; } extern pthread_mutex_t conn_lock; /* Connection timeout thread bits */ static pthread_t conn_timeout_tid; #define CONNS_PER_SLICE 100 #define TIMEOUT_MSG_SIZE (1 + sizeof(int)) static void *conn_timeout_thread(void *arg) { int i; conn *c; char buf[TIMEOUT_MSG_SIZE]; rel_time_t oldest_last_cmd; int sleep_time; useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE); while(1) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread at top of connection list\n"); oldest_last_cmd = current_time; for (i = 0; i < max_fds; i++) { if ((i % CONNS_PER_SLICE) == 0) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread sleeping for %ulus\n", (unsigned int)timeslice); usleep(timeslice); } if (!conns[i]) continue; c = conns[i]; if (!IS_TCP(c->transport)) continue; if (c->state != conn_new_cmd && c->state != conn_read) continue; if ((current_time - c->last_cmd_time) > settings.idle_timeout) { buf[0] = 't'; memcpy(&buf[1], &i, sizeof(int)); if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE) != TIMEOUT_MSG_SIZE) perror("Failed to write timeout to notify pipe"); } else { if (c->last_cmd_time < oldest_last_cmd) oldest_last_cmd = c->last_cmd_time; } } /* This is the soonest we could have another connection time out */ sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1; if (sleep_time <= 0) sleep_time = 1; if (settings.verbose > 2) fprintf(stderr, "idle timeout thread finished pass, sleeping for %ds\n", sleep_time); usleep((useconds_t) sleep_time * 1000000); } return NULL; } static int start_conn_timeout_thread() { int ret; if (settings.idle_timeout == 0) return -1; if ((ret = pthread_create(&conn_timeout_tid, NULL, conn_timeout_thread, NULL)) != 0) { fprintf(stderr, "Can't create idle connection timeout thread: %s\n", strerror(ret)); return -1; } return 0; } /* * Initializes the connections array. We don't actually allocate connection * structures until they're needed, so as to avoid wasting memory when the * maximum connection count is much higher than the actual number of * connections. * * This does end up wasting a few pointers' worth of memory for FDs that are * used for things other than connections, but that's worth it in exchange for * being able to directly index the conns array by FD. */ static void conn_init(void) { /* We're unlikely to see an FD much higher than maxconns. */ int next_fd = dup(1); if (next_fd < 0) { perror("Failed to duplicate file descriptor\n"); exit(1); } int headroom = 10; /* account for extra unexpected open FDs */ struct rlimit rl; max_fds = settings.maxconns + headroom + next_fd; /* But if possible, get the actual highest FD we can possibly ever see. */ if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { max_fds = rl.rlim_max; } else { fprintf(stderr, "Failed to query maximum file descriptor; " "falling back to maxconns\n"); } close(next_fd); if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) { fprintf(stderr, "Failed to allocate connection structures\n"); /* This is unrecoverable so bail out early. */ exit(1); } } static const char *prot_text(enum protocol prot) { char *rv = "unknown"; switch(prot) { case ascii_prot: rv = "ascii"; break; case binary_prot: rv = "binary"; break; case negotiating_prot: rv = "auto-negotiate"; break; } return rv; } void conn_close_idle(conn *c) { if (settings.idle_timeout > 0 && (current_time - c->last_cmd_time) > settings.idle_timeout) { if (c->state != conn_new_cmd && c->state != conn_read) { if (settings.verbose > 1) fprintf(stderr, "fd %d wants to timeout, but isn't in read state", c->sfd); return; } if (settings.verbose > 1) fprintf(stderr, "Closing idle fd %d\n", c->sfd); c->thread->stats.idle_kicks++; conn_set_state(c, conn_closing); drive_machine(c); } } /* bring conn back from a sidethread. could have had its event base moved. */ void conn_worker_readd(conn *c) { c->ev_flags = EV_READ | EV_PERSIST; event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c); event_base_set(c->thread->base, &c->event); c->state = conn_new_cmd; // TODO: call conn_cleanup/fail/etc if (event_add(&c->event, 0) == -1) { perror("event_add"); } #ifdef EXTSTORE // If we had IO objects, process if (c->io_wraplist) { //assert(c->io_wrapleft == 0); // assert no more to process conn_set_state(c, conn_mwrite); drive_machine(c); } #endif } conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base, void *ssl) { conn *c; assert(sfd >= 0 && sfd < max_fds); c = conns[sfd]; if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->read = NULL; c->sendmsg = NULL; c->write = NULL; c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats_state.conn_structs++; STATS_UNLOCK(); c->sfd = sfd; conns[sfd] = c; } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (transport == tcp_transport && init_state == conn_new_cmd) { if (getpeername(sfd, (struct sockaddr *) &c->request_addr, &c->request_addr_size)) { perror("getpeername"); memset(&c->request_addr, 0, sizeof(c->request_addr)); } } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } #ifdef TLS c->ssl = NULL; c->ssl_wbuf = NULL; c->ssl_enabled = false; #endif c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->sasl_started = false; c->last_cmd_time = current_time; /* initialize for idle kicker */ #ifdef EXTSTORE c->io_wraplist = NULL; c->io_wrapleft = 0; #endif c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; #ifdef TLS if (ssl) { c->ssl = (SSL*)ssl; c->read = ssl_read; c->sendmsg = ssl_sendmsg; c->write = ssl_write; c->ssl_enabled = true; SSL_set_info_callback(c->ssl, ssl_callback); } else #else // This must be NULL if TLS is not enabled. assert(ssl == NULL); #endif { c->read = tcp_read; c->sendmsg = tcp_sendmsg; c->write = tcp_write; } if (IS_UDP(transport)) { c->try_read_command = try_read_command_udp; } else { switch (c->protocol) { case ascii_prot: if (settings.auth_file == NULL) { c->authenticated = true; c->try_read_command = try_read_command_ascii; } else { c->authenticated = false; c->try_read_command = try_read_command_asciiauth; } break; case binary_prot: // binprot handles its own authentication via SASL parsing. c->authenticated = false; c->try_read_command = try_read_command_binary; break; case negotiating_prot: c->try_read_command = try_read_command_negotiate; break; } } event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { perror("event_add"); return NULL; } STATS_LOCK(); stats_state.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } #ifdef EXTSTORE static void recache_or_free(conn *c, io_wrap *wrap) { item *it; it = (item *)wrap->io.buf; bool do_free = true; if (wrap->active) { // If request never dispatched, free the read buffer but leave the // item header alone. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); c->io_wrapleft--; assert(c->io_wrapleft >= 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_aborted_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (wrap->miss) { // If request was ultimately a miss, unlink the header. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); item_unlink(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.miss_from_extstore++; if (wrap->badcrc) c->thread->stats.badcrc_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (settings.ext_recache_rate) { // hashvalue is cuddled during store uint32_t hv = (uint32_t)it->time; // opt to throw away rather than wait on a lock. void *hold_lock = item_trylock(hv); if (hold_lock != NULL) { item *h_it = wrap->hdr_it; uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE; // Item must be recently hit at least twice to recache. if (((h_it->it_flags & flags) == flags) && h_it->time > current_time - ITEM_UPDATE_INTERVAL && c->recache_counter++ % settings.ext_recache_rate == 0) { do_free = false; // In case it's been updated. it->exptime = h_it->exptime; it->it_flags &= ~ITEM_LINKED; it->refcount = 0; it->h_next = NULL; // might not be necessary. STORAGE_delete(c->thread->storage, h_it); item_replace(h_it, it, hv); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.recache_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } } if (hold_lock) item_trylock_unlock(hold_lock); } if (do_free) slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it)); wrap->io.buf = NULL; // sanity. wrap->io.next = NULL; wrap->next = NULL; wrap->active = false; // TODO: reuse lock and/or hv. item_remove(wrap->hdr_it); } #endif static void conn_release_items(conn *c) { assert(c != NULL); if (c->item) { item_remove(c->item); c->item = 0; } while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } if (c->suffixleft != 0) { for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) { do_cache_free(c->thread->suffix_cache, *(c->suffixcurr)); } } #ifdef EXTSTORE if (c->io_wraplist) { io_wrap *tmp = c->io_wraplist; while (tmp) { io_wrap *next = tmp->next; recache_or_free(c, tmp); do_cache_free(c->thread->io_cache, tmp); // lockless tmp = next; } c->io_wraplist = NULL; } #endif c->icurr = c->ilist; c->suffixcurr = c->suffixlist; } static void conn_cleanup(conn *c) { assert(c != NULL); conn_release_items(c); if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } if (c->sasl_conn) { assert(settings.sasl); sasl_dispose(&c->sasl_conn); c->sasl_conn = NULL; } if (IS_UDP(c->transport)) { conn_set_state(c, conn_read); } } /* * Frees a connection. */ void conn_free(conn *c) { if (c) { assert(c != NULL); assert(c->sfd >= 0 && c->sfd < max_fds); MEMCACHED_CONN_DESTROY(c); conns[c->sfd] = NULL; if (c->hdrbuf) free(c->hdrbuf); if (c->msglist) free(c->msglist); if (c->rbuf) free(c->rbuf); if (c->wbuf) free(c->wbuf); if (c->ilist) free(c->ilist); if (c->suffixlist) free(c->suffixlist); if (c->iov) free(c->iov); #ifdef TLS if (c->ssl_wbuf) c->ssl_wbuf = NULL; #endif free(c); } } static void conn_close(conn *c) { assert(c != NULL); /* delete the event, the socket and the conn */ event_del(&c->event); if (settings.verbose > 1) fprintf(stderr, "<%d connection closed.\n", c->sfd); conn_cleanup(c); MEMCACHED_CONN_RELEASE(c->sfd); conn_set_state(c, conn_closed); #ifdef TLS if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); } #endif close(c->sfd); pthread_mutex_lock(&conn_lock); allow_new_conns = true; pthread_mutex_unlock(&conn_lock); STATS_LOCK(); stats_state.curr_conns--; STATS_UNLOCK(); return; } /* * Shrinks a connection's buffers if they're too big. This prevents * periodic large "get" requests from permanently chewing lots of server * memory. * * This should only be called in between requests since it can wipe output * buffers! */ static void conn_shrink(conn *c) { assert(c != NULL); if (IS_UDP(c->transport)) return; if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) { char *newbuf; if (c->rcurr != c->rbuf) memmove(c->rbuf, c->rcurr, (size_t)c->rbytes); newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE); if (newbuf) { c->rbuf = newbuf; c->rsize = DATA_BUFFER_SIZE; } /* TODO check other branch... */ c->rcurr = c->rbuf; } if (c->isize > ITEM_LIST_HIGHWAT) { item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0])); if (newbuf) { c->ilist = newbuf; c->isize = ITEM_LIST_INITIAL; } /* TODO check error condition? */ } if (c->msgsize > MSG_LIST_HIGHWAT) { struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0])); if (newbuf) { c->msglist = newbuf; c->msgsize = MSG_LIST_INITIAL; } /* TODO check error condition? */ } if (c->iovsize > IOV_LIST_HIGHWAT) { struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0])); if (newbuf) { c->iov = newbuf; c->iovsize = IOV_LIST_INITIAL; } /* TODO check return value */ } } /** * Convert a state name to a human readable form. */ static const char *state_text(enum conn_states state) { const char* const statenames[] = { "conn_listening", "conn_new_cmd", "conn_waiting", "conn_read", "conn_parse_cmd", "conn_write", "conn_nread", "conn_swallow", "conn_closing", "conn_mwrite", "conn_closed", "conn_watch" }; return statenames[state]; } /* * Sets a connection's current state in the state machine. Any special * processing that needs to happen on certain state transitions can * happen here. */ static void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state >= conn_listening && state < conn_max_state); if (state != c->state) { if (settings.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } if (state == conn_write || state == conn_mwrite) { MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes); } c->state = state; } } /* * Ensures that there is room for another struct iovec in a connection's * iov list. * * Returns 0 on success, -1 on out-of-memory. */ static int ensure_iov_space(conn *c) { assert(c != NULL); if (c->iovused >= c->iovsize) { int i, iovnum; struct iovec *new_iov = (struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec)); if (! new_iov) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->iov = new_iov; c->iovsize *= 2; /* Point all the msghdr structures at the new list. */ for (i = 0, iovnum = 0; i < c->msgused; i++) { c->msglist[i].msg_iov = &c->iov[iovnum]; iovnum += c->msglist[i].msg_iovlen; } } return 0; } /* * Adds data to the list of pending data that will be written out to a * connection. * * Returns 0 on success, -1 on out-of-memory. * Note: This is a hot path for at least ASCII protocol. While there is * redundant code in splitting TCP/UDP handling, any reduction in steps has a * large impact for TCP connections. */ static int add_iov(conn *c, const void *buf, int len) { struct msghdr *m; int leftover; assert(c != NULL); if (IS_UDP(c->transport)) { do { m = &c->msglist[c->msgused - 1]; /* * Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes. */ /* We may need to start a new msghdr if this one is full. */ if (m->msg_iovlen == IOV_MAX || (c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; /* If the fragment is too big to fit in the datagram, split it up */ if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) { leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE; len -= leftover; } else { leftover = 0; } m = &c->msglist[c->msgused - 1]; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; buf = ((char *)buf) + len; len = leftover; } while (leftover > 0); } else { /* Optimized path for TCP connections */ m = &c->msglist[c->msgused - 1]; if (m->msg_iovlen == IOV_MAX) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; } return 0; } static int add_chunked_item_iovs(conn *c, item *it, int len) { assert(it->it_flags & ITEM_CHUNKED); item_chunk *ch = (item_chunk *) ITEM_schunk(it); while (ch) { int todo = (len > ch->used) ? ch->used : len; if (add_iov(c, ch->data, todo) != 0) { return -1; } ch = ch->next; len -= todo; } return 0; } /* * Constructs a set of UDP headers and attaches them to the outgoing messages. */ static int build_udp_headers(conn *c) { int i; unsigned char *hdr; assert(c != NULL); if (c->msgused > c->hdrsize) { void *new_hdrbuf; if (c->hdrbuf) { new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE); } else { new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE); } if (! new_hdrbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->hdrbuf = (unsigned char *)new_hdrbuf; c->hdrsize = c->msgused * 2; } hdr = c->hdrbuf; for (i = 0; i < c->msgused; i++) { c->msglist[i].msg_iov[0].iov_base = (void*)hdr; c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE; *hdr++ = c->request_id / 256; *hdr++ = c->request_id % 256; *hdr++ = i / 256; *hdr++ = i % 256; *hdr++ = c->msgused / 256; *hdr++ = c->msgused % 256; *hdr++ = 0; *hdr++ = 0; assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE); } return 0; } static void out_string(conn *c, const char *str) { size_t len; assert(c != NULL); if (c->noreply) { if (settings.verbose > 1) fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str); c->noreply = false; conn_set_state(c, conn_new_cmd); return; } if (settings.verbose > 1) fprintf(stderr, ">%d %s\n", c->sfd, str); /* Nuke a partial output... */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; add_msghdr(c); len = strlen(str); if ((len + 2) > c->wsize) { /* ought to be always enough. just fail for simplicity */ str = "SERVER_ERROR output line too long"; len = strlen(str); } memcpy(c->wbuf, str, len); memcpy(c->wbuf + len, "\r\n", 2); c->wbytes = len + 2; c->wcurr = c->wbuf; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; return; } /* * Outputs a protocol-specific "out of memory" error. For ASCII clients, * this is equivalent to out_string(). */ static void out_of_memory(conn *c, char *ascii_error) { const static char error_prefix[] = "SERVER_ERROR "; const static int error_prefix_len = sizeof(error_prefix) - 1; if (c->protocol == binary_prot) { /* Strip off the generic error prefix; it's irrelevant in binary */ if (!strncmp(ascii_error, error_prefix, error_prefix_len)) { ascii_error += error_prefix_len; } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0); } else { out_string(c, ascii_error); } } /* * we get here after reading the value in set/add/replace commands. The command * has been stored in c->cmd, and the item is ready in c->item. */ static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } /** * get a pointer to the start of the request struct for the current command */ static void* binary_get_request(conn *c) { char *ret = c->rcurr; ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen + c->binary_header.request.extlen); assert(ret >= c->rbuf); return ret; } /** * get a pointer to the key in this request */ static char* binary_get_key(conn *c) { return c->rcurr - (c->binary_header.request.keylen); } static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) { protocol_binary_response_header* header; assert(c); c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { /* This should never run out of memory because iov and msg lists * have minimum sizes big enough to hold an error response. */ out_of_memory(c, "SERVER_ERROR out of memory adding binary header"); return; } header = (protocol_binary_response_header *)c->wbuf; header->response.magic = (uint8_t)PROTOCOL_BINARY_RES; header->response.opcode = c->binary_header.request.opcode; header->response.keylen = (uint16_t)htons(key_len); header->response.extlen = (uint8_t)hdr_len; header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES; header->response.status = (uint16_t)htons(err); header->response.bodylen = htonl(body_len); header->response.opaque = c->opaque; header->response.cas = htonll(c->cas); if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d Writing bin response:", c->sfd); for (ii = 0; ii < sizeof(header->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n>%d ", c->sfd); } fprintf(stderr, " 0x%02x", header->bytes[ii]); } fprintf(stderr, "\n"); } add_iov(c, c->wbuf, sizeof(header->response)); } /** * Writes a binary error response. If errstr is supplied, it is used as the * error text; otherwise a generic description of the error status code is * included. */ static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow) { size_t len; if (!errstr) { switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } /* Form and send a response to a command over the binary protocol */ static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) { if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET || c->cmd == PROTOCOL_BINARY_CMD_GETK) { add_bin_header(c, 0, hlen, keylen, dlen); if(dlen > 0) { add_iov(c, d, dlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { conn_set_state(c, conn_new_cmd); } } static void complete_incr_bin(conn *c) { item *it; char *key; size_t nkey; /* Weird magic in add_delta forces me to pad here */ char tmpbuf[INCR_MAX_STORAGE_LEN]; uint64_t cas = 0; protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf; protocol_binary_request_incr* req = binary_get_request(c); assert(c != NULL); assert(c->wsize >= sizeof(*rsp)); /* fix byteorder in the request */ req->message.body.delta = ntohll(req->message.body.delta); req->message.body.initial = ntohll(req->message.body.initial); req->message.body.expiration = ntohl(req->message.body.expiration); key = binary_get_key(c); nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int i; fprintf(stderr, "incr "); for (i = 0; i < nkey; i++) { fprintf(stderr, "%c", key[i]); } fprintf(stderr, " %lld, %llu, %d\n", (long long)req->message.body.delta, (long long)req->message.body.initial, req->message.body.expiration); } if (c->binary_header.request.cas != 0) { cas = c->binary_header.request.cas; } switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT, req->message.body.delta, tmpbuf, &cas)) { case OK: rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10)); if (cas) { c->cas = cas; } write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); break; case NON_NUMERIC: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0); break; case EOM: out_of_memory(c, "SERVER_ERROR Out of memory incrementing value"); break; case DELTA_ITEM_NOT_FOUND: if (req->message.body.expiration != 0xffffffff) { /* Save some room for the response */ rsp->message.body.value = htonll(req->message.body.initial); snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)req->message.body.initial); int res = strlen(tmpbuf); it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration), res + 2); if (it != NULL) { memcpy(ITEM_data(it), tmpbuf, res); memcpy(ITEM_data(it) + res, "\r\n", 2); if (store_item(it, NREAD_ADD, c)) { c->cas = ITEM_get_cas(it); write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, NULL, 0); } item_remove(it); /* release our reference */ } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating new item"); } } else { pthread_mutex_lock(&c->thread->stats.mutex); if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } break; case DELTA_ITEM_CAS_MISMATCH: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; } } static void complete_update_bin(conn *c) { protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL; enum store_item_type ret = NOT_STORED; assert(c != NULL); item *it = c->item; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); /* We don't actually receive the trailing two characters in the bin * protocol, so we're going to just set them here */ if ((it->it_flags & ITEM_CHUNKED) == 0) { *(ITEM_data(it) + it->nbytes - 2) = '\r'; *(ITEM_data(it) + it->nbytes - 1) = '\n'; } else { assert(c->ritem); item_chunk *ch = (item_chunk *) c->ritem; if (ch->size == ch->used) ch = ch->next; assert(ch->size - ch->used >= 2); ch->data[ch->used] = '\r'; ch->data[ch->used + 1] = '\n'; ch->used += 2; } ret = store_item(it, c->cmd, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; } #endif switch (ret) { case STORED: /* Stored */ write_bin_response(c, NULL, 0, 0, 0); break; case EXISTS: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; case NOT_FOUND: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); break; case NOT_STORED: case TOO_LARGE: case NO_MEMORY: if (c->cmd == NREAD_ADD) { eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } else if(c->cmd == NREAD_REPLACE) { eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED; } write_bin_error(c, eno, NULL, 0); } item_remove(c->item); /* release the c->item reference */ c->item = 0; } static void write_bin_miss_response(conn *c, char *key, size_t nkey) { if (nkey) { char *ofs = c->wbuf + sizeof(protocol_binary_response_header); add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0, nkey, nkey); memcpy(ofs, key, nkey); add_iov(c, ofs, nkey); conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } } static void process_bin_get_or_touch(conn *c) { item *it; protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf; char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH || c->cmd == PROTOCOL_BINARY_CMD_GAT || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH); bool failed = false; if (settings.verbose > 1) { fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET"); if (fwrite(key, 1, nkey, stderr)) {} fputc('\n', stderr); } if (should_touch) { protocol_binary_request_touch *t = binary_get_request(c); time_t exptime = ntohl(t->message.body.expiration); it = item_touch(key, nkey, realtime(exptime), c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it) { /* the length has two unnecessary bytes ("\r\n") */ uint16_t keylen = 0; uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2); pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.get_cmds++; c->thread->stats.lru_hits[it->slabs_clsid]++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) { bodylen -= it->nbytes - 2; } else if (should_return_key) { bodylen += nkey; keylen = nkey; } add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen); rsp->message.header.response.cas = htonll(ITEM_get_cas(it)); // add the flags FLAGS_CONV(it, rsp->message.body.flags); rsp->message.body.flags = htonl(rsp->message.body.flags); add_iov(c, &rsp->message.body, sizeof(rsp->message.body)); if (should_return_key) { add_iov(c, ITEM_key(it), nkey); } if (should_return_value) { /* Add the data minus the CRLF */ #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { int iovcnt = 4; int iovst = c->iovused - 3; if (!should_return_key) { iovcnt = 3; iovst = c->iovused - 2; } if (_get_extstore(c, it, iovst, iovcnt) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); failed = true; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #endif } if (!failed) { conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; /* Remember this command so we can garbage collect it later */ #ifdef EXTSTORE if ((it->it_flags & ITEM_HDR) != 0 && should_return_value) { // Only have extstore clean if header and returning value. c->item = NULL; } else { c->item = it; } #else c->item = it; #endif } else { item_remove(it); } } else { failed = true; } if (failed) { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_cmds++; c->thread->stats.get_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0); } else { MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } if (c->noreply) { conn_set_state(c, conn_new_cmd); } else { if (should_return_key) { write_bin_miss_response(c, key, nkey); } else { write_bin_miss_response(c, NULL, 0); } } } if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } } static void append_bin_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *buf = c->stats.buffer + c->stats.offset; uint32_t bodylen = klen + vlen; protocol_binary_response_header header = { .response.magic = (uint8_t)PROTOCOL_BINARY_RES, .response.opcode = PROTOCOL_BINARY_CMD_STAT, .response.keylen = (uint16_t)htons(klen), .response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES, .response.bodylen = htonl(bodylen), .response.opaque = c->opaque }; memcpy(buf, header.bytes, sizeof(header.response)); buf += sizeof(header.response); if (klen > 0) { memcpy(buf, key, klen); buf += klen; if (vlen > 0) { memcpy(buf, val, vlen); } } c->stats.offset += sizeof(header.response) + bodylen; } static void append_ascii_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *pos = c->stats.buffer + c->stats.offset; uint32_t nbytes = 0; int remaining = c->stats.size - c->stats.offset; int room = remaining - 1; if (klen == 0 && vlen == 0) { nbytes = snprintf(pos, room, "END\r\n"); } else if (vlen == 0) { nbytes = snprintf(pos, room, "STAT %s\r\n", key); } else { nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val); } c->stats.offset += nbytes; } static bool grow_stats_buf(conn *c, size_t needed) { size_t nsize = c->stats.size; size_t available = nsize - c->stats.offset; bool rv = true; /* Special case: No buffer -- need to allocate fresh */ if (c->stats.buffer == NULL) { nsize = 1024; available = c->stats.size = c->stats.offset = 0; } while (needed > available) { assert(nsize > 0); nsize = nsize << 1; available = nsize - c->stats.offset; } if (nsize != c->stats.size) { char *ptr = realloc(c->stats.buffer, nsize); if (ptr) { c->stats.buffer = ptr; c->stats.size = nsize; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); rv = false; } } return rv; } static void append_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, const void *cookie) { /* value without a key is invalid */ if (klen == 0 && vlen > 0) { return ; } conn *c = (conn*)cookie; if (c->protocol == binary_prot) { size_t needed = vlen + klen + sizeof(protocol_binary_response_header); if (!grow_stats_buf(c, needed)) { return ; } append_bin_stats(key, klen, val, vlen, c); } else { size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n" if (!grow_stats_buf(c, needed)) { return ; } append_ascii_stats(key, klen, val, vlen, c); } assert(c->stats.offset <= c->stats.size); } static void process_bin_stat(conn *c) { char *subcommand = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int ii; fprintf(stderr, "<%d STATS ", c->sfd); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", subcommand[ii]); } fprintf(stderr, "\n"); } if (nkey == 0) { /* request all statistics */ server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strncmp(subcommand, "reset", 5) == 0) { stats_reset(); } else if (strncmp(subcommand, "settings", 8) == 0) { process_stat_settings(&append_stats, c); } else if (strncmp(subcommand, "detail", 6) == 0) { char *subcmd_pos = subcommand + 6; if (strncmp(subcmd_pos, " dump", 5) == 0) { int len; char *dump_buf = stats_prefix_dump(&len); if (dump_buf == NULL || len <= 0) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); if (dump_buf != NULL) free(dump_buf); return; } else { append_stats("detailed", strlen("detailed"), dump_buf, len, c); free(dump_buf); } } else if (strncmp(subcmd_pos, " on", 3) == 0) { settings.detail_enabled = 1; } else if (strncmp(subcmd_pos, " off", 4) == 0) { settings.detail_enabled = 0; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); return; } } else { if (get_stats(subcommand, nkey, &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } return; } /* Append termination package and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) { assert(c); c->substate = next_substate; c->rlbytes = c->keylen + extra; /* Ok... do we have room for the extras and the key in the input buffer? */ ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf; if (c->rlbytes > c->rsize - offset) { size_t nsize = c->rsize; size_t size = c->rlbytes + sizeof(protocol_binary_request_header); while (size > nsize) { nsize *= 2; } if (nsize != c->rsize) { if (settings.verbose > 1) { fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n", c->sfd, (unsigned long)c->rsize, (unsigned long)nsize); } char *newm = realloc(c->rbuf, nsize); if (newm == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose) { fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n", c->sfd); } conn_set_state(c, conn_closing); return; } c->rbuf= newm; /* rcurr should point to the same offset in the packet */ c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header); c->rsize = nsize; } if (c->rbuf != c->rcurr) { memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Repack input buffer\n", c->sfd); } } } /* preserve the header in the buffer.. */ c->ritem = c->rcurr + sizeof(protocol_binary_request_header); conn_set_state(c, conn_nread); } /* Just write an error message and disconnect the client */ static void handle_binary_protocol_error(conn *c) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0); if (settings.verbose) { fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n", c->binary_header.request.opcode, c->sfd); } c->write_and_go = conn_closing; } static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; c->authenticated = false; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } static void bin_list_sasl_mechs(conn *c) { // Guard against a disabled SASL. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } init_sasl_conn(c); const char *result_string = NULL; unsigned int string_length = 0; int result=sasl_listmech(c->sasl_conn, NULL, "", /* What to prepend the string with */ " ", /* What to separate mechanisms with */ "", /* What to append to the string */ &result_string, &string_length, NULL); if (result != SASL_OK) { /* Perhaps there's a better error for this... */ if (settings.verbose) { fprintf(stderr, "Failed to list SASL mechanisms.\n"); } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } write_bin_response(c, (char*)result_string, 0, 0, string_length); } static void process_bin_sasl_auth(conn *c) { // Guard for handling disabled SASL on the server. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } assert(c->binary_header.request.extlen == 0); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > MAX_SASL_MECH_LEN) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; return; } char *key = binary_get_key(c); assert(key); item *it = item_alloc(key, nkey, 0, 0, vlen+2); /* Can't use a chunked item for SASL authentication. */ if (it == 0 || (it->it_flags & ITEM_CHUNKED)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen); c->write_and_go = conn_swallow; return; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_reading_sasl_auth_data; } static void process_bin_complete_sasl_auth(conn *c) { assert(settings.sasl); const char *out = NULL; unsigned int outlen = 0; assert(c->item); init_sasl_conn(c); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > ((item*) c->item)->nkey) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } char mech[nkey+1]; memcpy(mech, ITEM_key((item*)c->item), nkey); mech[nkey] = 0x00; if (settings.verbose) fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen); const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item); if (vlen > ((item*) c->item)->nbytes) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } int result=-1; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_AUTH: result = sasl_server_start(c->sasl_conn, mech, challenge, vlen, &out, &outlen); c->sasl_started = (result == SASL_OK || result == SASL_CONTINUE); break; case PROTOCOL_BINARY_CMD_SASL_STEP: if (!c->sasl_started) { if (settings.verbose) { fprintf(stderr, "%d: SASL_STEP called but sasl_server_start " "not called for this connection!\n", c->sfd); } break; } result = sasl_server_step(c->sasl_conn, challenge, vlen, &out, &outlen); break; default: assert(false); /* CMD should be one of the above */ /* This code is pretty much impossible, but makes the compiler happier */ if (settings.verbose) { fprintf(stderr, "Unhandled command %d with challenge %s\n", c->cmd, challenge); } break; } item_unlink(c->item); if (settings.verbose) { fprintf(stderr, "sasl result code: %d\n", result); } switch(result) { case SASL_OK: c->authenticated = true; write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated")); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); break; case SASL_CONTINUE: add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen); if(outlen > 0) { add_iov(c, out, outlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; break; default: if (settings.verbose) fprintf(stderr, "Unknown sasl response: %d\n", result); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: rv = c->authenticated; } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } static void dispatch_bin_command(conn *c) { int protocol_error = 0; uint8_t extlen = c->binary_header.request.extlen; uint16_t keylen = c->binary_header.request.keylen; uint32_t bodylen = c->binary_header.request.bodylen; if (keylen > bodylen || keylen + extlen > bodylen) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0); c->write_and_go = conn_closing; return; } if (settings.sasl && !authenticated(c)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); c->write_and_go = conn_closing; return; } MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); c->noreply = true; /* binprot supports 16bit keys, but internals are still 8bit */ if (keylen > KEY_MAX_LENGTH) { handle_binary_protocol_error(c); return; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_SETQ: c->cmd = PROTOCOL_BINARY_CMD_SET; break; case PROTOCOL_BINARY_CMD_ADDQ: c->cmd = PROTOCOL_BINARY_CMD_ADD; break; case PROTOCOL_BINARY_CMD_REPLACEQ: c->cmd = PROTOCOL_BINARY_CMD_REPLACE; break; case PROTOCOL_BINARY_CMD_DELETEQ: c->cmd = PROTOCOL_BINARY_CMD_DELETE; break; case PROTOCOL_BINARY_CMD_INCREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_INCREMENT; break; case PROTOCOL_BINARY_CMD_DECREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_DECREMENT; break; case PROTOCOL_BINARY_CMD_QUITQ: c->cmd = PROTOCOL_BINARY_CMD_QUIT; break; case PROTOCOL_BINARY_CMD_FLUSHQ: c->cmd = PROTOCOL_BINARY_CMD_FLUSH; break; case PROTOCOL_BINARY_CMD_APPENDQ: c->cmd = PROTOCOL_BINARY_CMD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPENDQ: c->cmd = PROTOCOL_BINARY_CMD_PREPEND; break; case PROTOCOL_BINARY_CMD_GETQ: c->cmd = PROTOCOL_BINARY_CMD_GET; break; case PROTOCOL_BINARY_CMD_GETKQ: c->cmd = PROTOCOL_BINARY_CMD_GETK; break; case PROTOCOL_BINARY_CMD_GATQ: c->cmd = PROTOCOL_BINARY_CMD_GAT; break; case PROTOCOL_BINARY_CMD_GATKQ: c->cmd = PROTOCOL_BINARY_CMD_GATK; break; default: c->noreply = false; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_VERSION: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, VERSION, 0, 0, strlen(VERSION)); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_FLUSH: if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) { bin_read_key(c, bin_read_flush_exptime, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_NOOP: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_REPLACE: if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) { bin_read_key(c, bin_reading_set_header, 8); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETK: if (extlen == 0 && bodylen == keylen && keylen > 0) { bin_read_key(c, bin_reading_get_key, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_DELETE: if (keylen > 0 && extlen == 0 && bodylen == keylen) { bin_read_key(c, bin_reading_del_header, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_INCREMENT: case PROTOCOL_BINARY_CMD_DECREMENT: if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) { bin_read_key(c, bin_reading_incr_header, 20); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_APPEND: case PROTOCOL_BINARY_CMD_PREPEND: if (keylen > 0 && extlen == 0) { bin_read_key(c, bin_reading_set_header, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_STAT: if (extlen == 0) { bin_read_key(c, bin_reading_stat, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_QUIT: if (keylen == 0 && extlen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); c->write_and_go = conn_closing; if (c->noreply) { conn_set_state(c, conn_closing); } } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: if (extlen == 0 && keylen == 0 && bodylen == 0) { bin_list_sasl_mechs(c); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_AUTH: case PROTOCOL_BINARY_CMD_SASL_STEP: if (extlen == 0 && keylen != 0) { bin_read_key(c, bin_reading_sasl_auth, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_TOUCH: case PROTOCOL_BINARY_CMD_GAT: case PROTOCOL_BINARY_CMD_GATQ: case PROTOCOL_BINARY_CMD_GATK: case PROTOCOL_BINARY_CMD_GATKQ: if (extlen == 4 && keylen != 0) { bin_read_key(c, bin_reading_touch_key, 4); } else { protocol_error = 1; } break; default: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, bodylen); } if (protocol_error) handle_binary_protocol_error(c); } static void process_bin_update(conn *c) { char *key; int nkey; int vlen; item *it; protocol_binary_request_set* req = binary_get_request(c); assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; /* fix byteorder in the request */ req->message.body.flags = ntohl(req->message.body.flags); req->message.body.expiration = ntohl(req->message.body.expiration); vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen); if (settings.verbose > 1) { int ii; if (c->cmd == PROTOCOL_BINARY_CMD_ADD) { fprintf(stderr, "<%d ADD ", c->sfd); } else if (c->cmd == PROTOCOL_BINARY_CMD_SET) { fprintf(stderr, "<%d SET ", c->sfd); } else { fprintf(stderr, "<%d REPLACE ", c->sfd); } for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, " Value len is %d", vlen); fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, req->message.body.flags, realtime(req->message.body.expiration), vlen+2); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* This error generating method eats the swallow value. Add here. */ c->sbytes = vlen; status = NO_MEMORY; } /* FIXME: losing c->cmd since it's translated below. refactor? */ LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, 0, key, nkey, req->message.body.expiration, ITEM_clsid(it), c->sfd); /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (c->cmd == PROTOCOL_BINARY_CMD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_ADD: c->cmd = NREAD_ADD; break; case PROTOCOL_BINARY_CMD_SET: c->cmd = NREAD_SET; break; case PROTOCOL_BINARY_CMD_REPLACE: c->cmd = NREAD_REPLACE; break; default: assert(0); } if (ITEM_get_cas(it) != 0) { c->cmd = NREAD_CAS; } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_append_prepend(conn *c) { char *key; int nkey; int vlen; item *it; assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; vlen = c->binary_header.request.bodylen - nkey; if (settings.verbose > 1) { fprintf(stderr, "Value len is %d\n", vlen); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, 0, 0, vlen+2); if (it == 0) { if (! item_size_ok(nkey, 0, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* OOM calls eat the swallow value. Add here. */ c->sbytes = vlen; } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_APPEND: c->cmd = NREAD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPEND: c->cmd = NREAD_PREPEND; break; default: assert(0); } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_flush(conn *c) { time_t exptime = 0; protocol_binary_request_flush* req = binary_get_request(c); rel_time_t new_oldest = 0; if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } if (c->binary_header.request.extlen == sizeof(req->message.body)) { exptime = ntohl(req->message.body.expiration); } if (exptime > 0) { new_oldest = realtime(exptime); } else { new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_response(c, NULL, 0, 0, 0); } static void process_bin_delete(conn *c) { item *it; uint32_t hv; protocol_binary_request_delete* req = binary_get_request(c); char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; assert(c != NULL); if (settings.verbose > 1) { int ii; fprintf(stderr, "Deleting "); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { uint64_t cas = ntohll(req->message.header.request.cas); if (cas == 0 || cas == ITEM_get_cas(it)) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); write_bin_response(c, NULL, 0, 0, 0); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); } do_item_remove(it); /* release our reference */ } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } item_unlock(hv); } static void complete_nread_binary(conn *c) { assert(c != NULL); assert(c->cmd >= 0); switch(c->substate) { case bin_reading_set_header: if (c->cmd == PROTOCOL_BINARY_CMD_APPEND || c->cmd == PROTOCOL_BINARY_CMD_PREPEND) { process_bin_append_prepend(c); } else { process_bin_update(c); } break; case bin_read_set_value: complete_update_bin(c); break; case bin_reading_get_key: case bin_reading_touch_key: process_bin_get_or_touch(c); break; case bin_reading_stat: process_bin_stat(c); break; case bin_reading_del_header: process_bin_delete(c); break; case bin_reading_incr_header: complete_incr_bin(c); break; case bin_read_flush_exptime: process_bin_flush(c); break; case bin_reading_sasl_auth: process_bin_sasl_auth(c); break; case bin_reading_sasl_auth_data: process_bin_complete_sasl_auth(c); break; default: fprintf(stderr, "Not handling substate %d\n", c->substate); assert(0); } } static void reset_cmd_handler(conn *c) { c->cmd = -1; c->substate = bin_no_state; if(c->item != NULL) { item_remove(c->item); c->item = NULL; } conn_shrink(c); if (c->rbytes > 0) { conn_set_state(c, conn_parse_cmd); } else { conn_set_state(c, conn_waiting); } } static void complete_nread(conn *c) { assert(c != NULL); assert(c->protocol == ascii_prot || c->protocol == binary_prot); if (c->protocol == ascii_prot) { complete_nread_ascii(c); } else if (c->protocol == binary_prot) { complete_nread_binary(c); } } /* Destination must always be chunked */ /* This should be part of item.c */ static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) { item_chunk *dch = (item_chunk *) ITEM_schunk(d_it); /* Advance dch until we find free space */ while (dch->size == dch->used) { if (dch->next) { dch = dch->next; } else { break; } } if (s_it->it_flags & ITEM_CHUNKED) { int remain = len; item_chunk *sch = (item_chunk *) ITEM_schunk(s_it); int copied = 0; /* Fills dch's to capacity, not straight copy sch in case data is * being added or removed (ie append/prepend) */ while (sch && dch && remain) { assert(dch->used <= dch->size); int todo = (dch->size - dch->used < sch->used - copied) ? dch->size - dch->used : sch->used - copied; if (remain < todo) todo = remain; memcpy(dch->data + dch->used, sch->data + copied, todo); dch->used += todo; copied += todo; remain -= todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, remain); if (tch) { dch = tch; } else { return -1; } } assert(copied <= sch->used); if (copied == sch->used) { copied = 0; sch = sch->next; } } /* assert that the destination had enough space for the source */ assert(remain == 0); } else { int done = 0; /* Fill dch's via a non-chunked item. */ while (len > done && dch) { int todo = (dch->size - dch->used < len - done) ? dch->size - dch->used : len - done; //assert(dch->size - dch->used != 0); memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo); done += todo; dch->used += todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, len - done); if (tch) { dch = tch; } else { return -1; } } } assert(len == done); } return 0; } static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) { if (comm == NREAD_APPEND) { if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes); memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes); } } else { /* NREAD_PREPEND */ if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes); memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes); } } return 0; } /* * Stores an item in the cache according to the semantics of one of the set * commands. In threaded mode, this is protected by the cache lock. * * Returns the state of storage. */ enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) { char *key = ITEM_key(it); item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE); enum store_item_type stored = NOT_STORED; item *new_it = NULL; uint32_t flags; if (old_it != NULL && comm == NREAD_ADD) { /* add only adds a nonexistent item, but promote to head of LRU */ do_item_update(old_it); } else if (!old_it && (comm == NREAD_REPLACE || comm == NREAD_APPEND || comm == NREAD_PREPEND)) { /* replace only replaces an existing value; don't store */ } else if (comm == NREAD_CAS) { /* validate cas operation */ if(old_it == NULL) { // LRU expired stored = NOT_FOUND; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.cas_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) { // cas validates // it and old_it may belong to different classes. // I'm updating the stats for the one that's getting pushed out pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); stored = STORED; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++; pthread_mutex_unlock(&c->thread->stats.mutex); if(settings.verbose > 1) { fprintf(stderr, "CAS: failure: expected %llu, got %llu\n", (unsigned long long)ITEM_get_cas(old_it), (unsigned long long)ITEM_get_cas(it)); } stored = EXISTS; } } else { int failed_alloc = 0; /* * Append - combine new and old record into single one. Here it's * atomic and thread-safe. */ if (comm == NREAD_APPEND || comm == NREAD_PREPEND) { /* * Validate CAS */ if (ITEM_get_cas(it) != 0) { // CAS much be equal if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) { stored = EXISTS; } } #ifdef EXTSTORE if ((old_it->it_flags & ITEM_HDR) != 0) { /* block append/prepend from working with extstore-d items. * also don't replace the header with the append chunk * accidentally, so mark as a failed_alloc. */ failed_alloc = 1; } else #endif if (stored == NOT_STORED) { /* we have it and old_it here - alloc memory to hold both */ /* flags was already lost - so recover them from ITEM_suffix(it) */ FLAGS_CONV(old_it, flags); new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */); /* copy data from it and old_it to new_it */ if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) { failed_alloc = 1; stored = NOT_STORED; // failed data copy, free up. if (new_it != NULL) item_remove(new_it); } else { it = new_it; } } } if (stored == NOT_STORED && failed_alloc == 0) { if (old_it != NULL) { STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); } else { do_item_link(it, hv); } c->cas = ITEM_get_cas(it); stored = STORED; } } if (old_it != NULL) do_item_remove(old_it); /* release our reference */ if (new_it != NULL) do_item_remove(new_it); if (stored == STORED) { c->cas = ITEM_get_cas(it); } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it), c->sfd); return stored; } typedef struct token_s { char *value; size_t length; } token_t; #define COMMAND_TOKEN 0 #define SUBCOMMAND_TOKEN 1 #define KEY_TOKEN 1 #define MAX_TOKENS 8 /* * Tokenize the command string by replacing whitespace with '\0' and update * the token array tokens with pointer to start of each token and length. * Returns total number of tokens. The last valid token is the terminal * token (value points to the first unprocessed character of the string and * length zero). * * Usage example: * * while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) { * for(int ix = 0; tokens[ix].length != 0; ix++) { * ... * } * ncommand = tokens[ix].value - command; * command = tokens[ix].value; * } */ static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) { char *s, *e; size_t ntokens = 0; size_t len = strlen(command); unsigned int i = 0; assert(command != NULL && tokens != NULL && max_tokens > 1); s = e = command; for (i = 0; i < len; i++) { if (*e == ' ') { if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; *e = '\0'; if (ntokens == max_tokens - 1) { e++; s = e; /* so we don't add an extra token */ break; } } s = e + 1; } e++; } if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; } /* * If we scanned the whole string, the terminal value pointer is null, * otherwise it is the first unprocessed character. */ tokens[ntokens].value = *e == '\0' ? NULL : e; tokens[ntokens].length = 0; ntokens++; return ntokens; } /* set up a connection to write a buffer then free it, used for stats */ static void write_and_free(conn *c, char *buf, int bytes) { if (buf) { c->write_and_free = buf; c->wcurr = buf; c->wbytes = bytes; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; } else { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } } static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens) { int noreply_index = ntokens - 2; /* NOTE: this function is not the first place where we are going to send the reply. We could send it instead from process_command() if the request line has wrong number of tokens. However parsing malformed line for "noreply" option is not reliable anyway, so it can't be helped. */ if (tokens[noreply_index].value && strcmp(tokens[noreply_index].value, "noreply") == 0) { c->noreply = true; } return c->noreply; } void append_stat(const char *name, ADD_STAT add_stats, conn *c, const char *fmt, ...) { char val_str[STAT_VAL_LEN]; int vlen; va_list ap; assert(name); assert(add_stats); assert(c); assert(fmt); va_start(ap, fmt); vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap); va_end(ap); add_stats(name, strlen(name), val_str, vlen, c); } inline static void process_stats_detail(conn *c, const char *command) { assert(c != NULL); if (strcmp(command, "on") == 0) { settings.detail_enabled = 1; out_string(c, "OK"); } else if (strcmp(command, "off") == 0) { settings.detail_enabled = 0; out_string(c, "OK"); } else if (strcmp(command, "dump") == 0) { int len; char *stats = stats_prefix_dump(&len); write_and_free(c, stats, len); } else { out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump"); } } /* return server specific stats only */ static void server_stats(ADD_STAT add_stats, conn *c) { pid_t pid = getpid(); rel_time_t now = current_time; struct thread_stats thread_stats; threadlocal_stats_aggregate(&thread_stats); struct slab_stats slab_stats; slab_stats_aggregate(&thread_stats, &slab_stats); #ifdef EXTSTORE struct extstore_stats st; #endif #ifndef WIN32 struct rusage usage; getrusage(RUSAGE_SELF, &usage); #endif /* !WIN32 */ STATS_LOCK(); APPEND_STAT("pid", "%lu", (long)pid); APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL); APPEND_STAT("time", "%ld", now + (long)process_started); APPEND_STAT("version", "%s", VERSION); APPEND_STAT("libevent", "%s", event_get_version()); APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *))); #ifndef WIN32 append_stat("rusage_user", add_stats, c, "%ld.%06ld", (long)usage.ru_utime.tv_sec, (long)usage.ru_utime.tv_usec); append_stat("rusage_system", add_stats, c, "%ld.%06ld", (long)usage.ru_stime.tv_sec, (long)usage.ru_stime.tv_usec); #endif /* !WIN32 */ APPEND_STAT("max_connections", "%d", settings.maxconns); APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1); APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns); if (settings.maxconns_fast) { APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns); } APPEND_STAT("connection_structures", "%u", stats_state.conn_structs); APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds); APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds); APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds); APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds); APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds); APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits); APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses); APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired); APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed); #ifdef EXTSTORE if (c->thread->storage) { APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore); APPEND_STAT("get_aborted_extstore", "%llu", (unsigned long long)thread_stats.get_aborted_extstore); APPEND_STAT("get_oom_extstore", "%llu", (unsigned long long)thread_stats.get_oom_extstore); APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore); APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore); APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore); } #endif APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses); APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits); APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses); APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits); APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses); APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits); APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses); APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits); APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval); APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits); APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses); APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds); APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors); if (settings.idle_timeout) { APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks); } APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read); APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written); APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns); APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num); APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us); APPEND_STAT("threads", "%d", settings.num_threads); APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields); APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level); APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes); APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding); if (settings.slab_reassign) { APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues); APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues); APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem); APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim); APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items); APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes); APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running); APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved); } if (settings.lru_crawler) { APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running); APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts); } if (settings.lru_maintainer_thread) { APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles); } APPEND_STAT("malloc_fails", "%llu", (unsigned long long)stats.malloc_fails); APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped); APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written); APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped); APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent); STATS_UNLOCK(); #ifdef EXTSTORE if (c->thread->storage) { STATS_LOCK(); APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost); APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues); APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped); STATS_UNLOCK(); extstore_get_stats(c->thread->storage, &st); APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs); APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions); APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims); APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free); APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used); APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted); APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read); APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written); APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used); APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted); APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written); APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read); APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used); APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented); APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size)); APPEND_STAT("extstore_io_queue", "%llu", (unsigned long long)(st.io_queue)); } #endif #ifdef TLS if (settings.ssl_enabled) { SSL_LOCK(); APPEND_STAT("time_since_server_cert_refresh", "%u", now - settings.ssl_last_cert_refresh_time); SSL_UNLOCK(); } #endif } static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("auth_enabled_ascii", "%s", settings.auth_file ? settings.auth_file : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio); APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", "no"); // setting is dead, cannot be yes. #ifdef HAVE_DROP_PRIVILEGES APPEND_STAT("drop_privileges", "%s", settings.drop_privileges ? "yes" : "no"); #endif #ifdef EXTSTORE APPEND_STAT("ext_item_size", "%u", settings.ext_item_size); APPEND_STAT("ext_item_age", "%u", settings.ext_item_age); APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl); APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate); APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size); APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under); APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under); APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag); APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio); APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no"); #endif #ifdef TLS APPEND_STAT("ssl_enabled", "%s", settings.ssl_enabled ? "yes" : "no"); APPEND_STAT("ssl_chain_cert", "%s", settings.ssl_chain_cert); APPEND_STAT("ssl_key", "%s", settings.ssl_key); APPEND_STAT("ssl_verify_mode", "%d", settings.ssl_verify_mode); APPEND_STAT("ssl_keyformat", "%d", settings.ssl_keyformat); APPEND_STAT("ssl_ciphers", "%s", settings.ssl_ciphers ? settings.ssl_ciphers : "NULL"); APPEND_STAT("ssl_ca_cert", "%s", settings.ssl_ca_cert ? settings.ssl_ca_cert : "NULL"); APPEND_STAT("ssl_wbuf_size", "%u", settings.ssl_wbuf_size); #endif } static int nz_strcmp(int nzlength, const char *nz, const char *z) { int zlength=strlen(z); return (zlength == nzlength) && (strncmp(nz, z, zlength) == 0) ? 0 : -1; } static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c) { bool ret = true; if (add_stats != NULL) { if (!stat_type) { /* prepare general statistics for the engine */ STATS_LOCK(); APPEND_STAT("bytes", "%llu", (unsigned long long)stats_state.curr_bytes); APPEND_STAT("curr_items", "%llu", (unsigned long long)stats_state.curr_items); APPEND_STAT("total_items", "%llu", (unsigned long long)stats.total_items); STATS_UNLOCK(); APPEND_STAT("slab_global_page_pool", "%u", global_page_pool_size(NULL)); item_stats_totals(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "items") == 0) { item_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "slabs") == 0) { slabs_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes") == 0) { item_stats_sizes(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_enable") == 0) { item_stats_sizes_enable(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_disable") == 0) { item_stats_sizes_disable(add_stats, c); } else { ret = false; } } else { ret = false; } return ret; } static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, sizeof(addr_text) - 1); addr_text[sizeof(addr_text)-1] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } } static void conn_to_str(const conn *c, char *addr, char *svr_addr) { if (!c) { strcpy(addr, "<null>"); } else if (c->state == conn_closed) { strcpy(addr, "<closed>"); } else { struct sockaddr_in6 local_addr; struct sockaddr *sock_addr = (void *)&c->request_addr; /* For listen ports and idle UDP ports, show listen address */ if (c->state == conn_listening || (IS_UDP(c->transport) && c->state == conn_read)) { socklen_t local_addr_len = sizeof(local_addr); if (getsockname(c->sfd, (struct sockaddr *)&local_addr, &local_addr_len) == 0) { sock_addr = (struct sockaddr *)&local_addr; } } get_conn_text(c, sock_addr->sa_family, addr, sock_addr); if (c->state != conn_listening && !(IS_UDP(c->transport) && c->state == conn_read)) { struct sockaddr_storage svr_sock_addr; socklen_t svr_addr_len = sizeof(svr_sock_addr); getsockname(c->sfd, (struct sockaddr *)&svr_sock_addr, &svr_addr_len); get_conn_text(c, svr_sock_addr.ss_family, svr_addr, (struct sockaddr *)&svr_sock_addr); } } } static void process_stats_conns(ADD_STAT add_stats, void *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; size_t extras_len = sizeof("unix:") + sizeof("65535"); char addr[MAXPATHLEN + extras_len]; char svr_addr[MAXPATHLEN + extras_len]; int klen = 0, vlen = 0; assert(add_stats); for (i = 0; i < max_fds; i++) { if (conns[i]) { /* This is safe to do unlocked because conns are never freed; the * worst that'll happen will be a minor inconsistency in the * output -- not worth the complexity of the locking that'd be * required to prevent it. */ if (IS_UDP(conns[i]->transport)) { APPEND_NUM_STAT(i, "UDP", "%s", "UDP"); } if (conns[i]->state != conn_closed) { conn_to_str(conns[i], addr, svr_addr); APPEND_NUM_STAT(i, "addr", "%s", addr); if (conns[i]->state != conn_listening && !(IS_UDP(conns[i]->transport) && conns[i]->state == conn_read)) { APPEND_NUM_STAT(i, "listen_addr", "%s", svr_addr); } APPEND_NUM_STAT(i, "state", "%s", state_text(conns[i]->state)); APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d", current_time - conns[i]->last_cmd_time); } } } } #ifdef EXTSTORE static void process_extstore_stats(ADD_STAT add_stats, conn *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; int klen = 0, vlen = 0; struct extstore_stats st; assert(add_stats); void *storage = c->thread->storage; extstore_get_stats(storage, &st); st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data)); extstore_get_page_data(storage, &st); for (i = 0; i < st.page_count; i++) { APPEND_NUM_STAT(i, "version", "%llu", (unsigned long long) st.page_data[i].version); APPEND_NUM_STAT(i, "bytes", "%llu", (unsigned long long) st.page_data[i].bytes_used); APPEND_NUM_STAT(i, "bucket", "%u", st.page_data[i].bucket); APPEND_NUM_STAT(i, "free_bucket", "%u", st.page_data[i].free_bucket); } } #endif static void process_stat(conn *c, token_t *tokens, const size_t ntokens) { const char *subcommand = tokens[SUBCOMMAND_TOKEN].value; assert(c != NULL); if (ntokens < 2) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (ntokens == 2) { server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strcmp(subcommand, "reset") == 0) { stats_reset(); out_string(c, "RESET"); return ; } else if (strcmp(subcommand, "detail") == 0) { /* NOTE: how to tackle detail with binary? */ if (ntokens < 4) process_stats_detail(c, ""); /* outputs the error message */ else process_stats_detail(c, tokens[2].value); /* Output already generated */ return ; } else if (strcmp(subcommand, "settings") == 0) { process_stat_settings(&append_stats, c); } else if (strcmp(subcommand, "cachedump") == 0) { char *buf; unsigned int bytes, id, limit = 0; if (!settings.dump_enabled) { out_string(c, "CLIENT_ERROR stats cachedump not allowed"); return; } if (ntokens < 5) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (!safe_strtoul(tokens[2].value, &id) || !safe_strtoul(tokens[3].value, &limit)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (id >= MAX_NUMBER_OF_SLAB_CLASSES) { out_string(c, "CLIENT_ERROR Illegal slab id"); return; } buf = item_cachedump(id, limit, &bytes); write_and_free(c, buf, bytes); return ; } else if (strcmp(subcommand, "conns") == 0) { process_stats_conns(&append_stats, c); #ifdef EXTSTORE } else if (strcmp(subcommand, "extstore") == 0) { process_extstore_stats(&append_stats, c); #endif } else { /* getting here means that the subcommand is either engine specific or is invalid. query the engine and see. */ if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { out_string(c, "ERROR"); } return ; } /* append terminator and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } /* client flags == 0 means use no storage for client flags */ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) { char *p = suffix; *p = ' '; p++; if (FLAGS_SIZE(it) == 0) { *p = '0'; p++; } else { p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p); } *p = ' '; p = itoa_u32(nbytes-2, p+1); if (return_cas) { *p = ' '; p = itoa_u64(ITEM_get_cas(it), p+1); } *p = '\r'; *(p+1) = '\n'; *(p+2) = '\0'; return (p - suffix) + 2; } #define IT_REFCOUNT_LIMIT 60000 static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) { item *it; if (should_touch) { it = item_touch(key, nkey, exptime, c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it && it->refcount > IT_REFCOUNT_LIMIT) { item_remove(it); it = NULL; } return it; } static inline int _ascii_get_expand_ilist(conn *c, int i) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } } return 0; } static inline char *_ascii_get_suffix_buf(conn *c, int i) { char *suffix; /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return NULL; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); return NULL; } *(c->suffixlist + i) = suffix; return suffix; } #ifdef EXTSTORE // FIXME: This runs in the IO thread. to get better IO performance this should // simply mark the io wrapper with the return value and decrement wrapleft, if // zero redispatching. Still a bit of work being done in the side thread but // minimized at least. static void _get_extstore_cb(void *e, obj_io *io, int ret) { // FIXME: assumes success io_wrap *wrap = (io_wrap *)io->data; conn *c = wrap->c; assert(wrap->active == true); item *read_it = (item *)io->buf; bool miss = false; // TODO: How to do counters for hit/misses? if (ret < 1) { miss = true; } else { uint32_t crc2; uint32_t crc = (uint32_t) read_it->exptime; int x; // item is chunked, crc the iov's if (io->iov != NULL) { // first iov is the header, which we don't use beyond crc crc2 = crc32c(0, (char *)io->iov[0].iov_base+STORE_OFFSET, io->iov[0].iov_len-STORE_OFFSET); // make sure it's not sent. hack :( io->iov[0].iov_len = 0; for (x = 1; x < io->iovcnt; x++) { crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len); } } else { crc2 = crc32c(0, (char *)read_it+STORE_OFFSET, io->len-STORE_OFFSET); } if (crc != crc2) { miss = true; wrap->badcrc = true; } } if (miss) { int i; struct iovec *v; // TODO: This should be movable to the worker thread. if (c->protocol == binary_prot) { protocol_binary_response_header *header = (protocol_binary_response_header *)c->wbuf; // this zeroes out the iovecs since binprot never stacks them. if (header->response.keylen) { write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey); } else { write_bin_miss_response(c, 0, 0); } } else { for (i = 0; i < wrap->iovec_count; i++) { v = &c->iov[wrap->iovec_start + i]; v->iov_len = 0; v->iov_base = NULL; } } wrap->miss = true; } else { assert(read_it->slabs_clsid != 0); // kill \r\n for binprot if (io->iov == NULL) { c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it); if (c->protocol == binary_prot) c->iov[wrap->iovec_data].iov_len -= 2; } else { // FIXME: Might need to go back and ensure chunked binprots don't // ever span two chunks for the final \r\n if (c->protocol == binary_prot) { if (io->iov[io->iovcnt-1].iov_len >= 2) { io->iov[io->iovcnt-1].iov_len -= 2; } else { io->iov[io->iovcnt-1].iov_len = 0; io->iov[io->iovcnt-2].iov_len -= 1; } } } wrap->miss = false; // iov_len is already set // TODO: Should do that here instead and cuddle in the wrap object } c->io_wrapleft--; wrap->active = false; //assert(c->io_wrapleft >= 0); // All IO's have returned, lets re-attach this connection to our original // thread. if (c->io_wrapleft == 0) { assert(c->io_queued == true); c->io_queued = false; redispatch_conn(c); } } // FIXME: This completely breaks UDP support. static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) { #ifdef NEED_ALIGN item_hdr hdr; memcpy(&hdr, ITEM_data(it), sizeof(hdr)); #else item_hdr *hdr = (item_hdr *)ITEM_data(it); #endif size_t ntotal = ITEM_ntotal(it); unsigned int clsid = slabs_clsid(ntotal); item *new_it; bool chunked = false; if (ntotal > settings.slab_chunk_size_max) { // Pull a chunked item header. uint32_t flags; FLAGS_CONV(it, flags); new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes); assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED)); chunked = true; } else { new_it = do_item_alloc_pull(ntotal, clsid); } if (new_it == NULL) return -1; assert(!c->io_queued); // FIXME: debugging. // so we can free the chunk on a miss new_it->slabs_clsid = clsid; io_wrap *io = do_cache_alloc(c->thread->io_cache); io->active = true; io->miss = false; io->badcrc = false; // io_wrap owns the reference for this object now. io->hdr_it = it; // FIXME: error handling. // The offsets we'll wipe on a miss. io->iovec_start = iovst; io->iovec_count = iovcnt; // This is probably super dangerous. keep it at 0 and fill into wrap // object? if (chunked) { unsigned int ciovcnt = 1; size_t remain = new_it->nbytes; item_chunk *chunk = (item_chunk *) ITEM_schunk(new_it); io->io.iov = &c->iov[c->iovused]; // fill the header so we can get the full data + crc back. add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes); while (remain > 0) { chunk = do_item_alloc_chunk(chunk, remain); if (chunk == NULL) { item_remove(new_it); do_cache_free(c->thread->io_cache, io); return -1; } add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size); chunk->used = (remain < chunk->size) ? remain : chunk->size; remain -= chunk->size; ciovcnt++; } io->io.iovcnt = ciovcnt; // header object was already accounted for, remove one from total io->iovec_count += ciovcnt-1; } else { io->io.iov = NULL; io->iovec_data = c->iovused; add_iov(c, "", it->nbytes); } io->io.buf = (void *)new_it; // The offset we'll fill in on a hit. io->c = c; // We need to stack the sub-struct IO's together as well. if (c->io_wraplist) { io->io.next = &c->io_wraplist->io; } else { io->io.next = NULL; } // IO queue for this connection. io->next = c->io_wraplist; c->io_wraplist = io; assert(c->io_wrapleft >= 0); c->io_wrapleft++; // reference ourselves for the callback. io->io.data = (void *)io; // Now, fill in io->io based on what was in our header. #ifdef NEED_ALIGN io->io.page_version = hdr.page_version; io->io.page_id = hdr.page_id; io->io.offset = hdr.offset; #else io->io.page_version = hdr->page_version; io->io.page_id = hdr->page_id; io->io.offset = hdr->offset; #endif io->io.len = ntotal; io->io.mode = OBJ_IO_READ; io->io.cb = _get_extstore_cb; //fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data); // FIXME: This stat needs to move to reflect # of flash hits vs misses // for now it's a good gauge on how often we request out to flash at // least. pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); return 0; } #endif /* ntokens is overwritten here... shrug.. */ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) { char *key; size_t nkey; int i = 0; int si = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; int32_t exptime_int = 0; rel_time_t exptime = 0; bool fail_length = false; assert(c != NULL); if (should_touch) { // For get and touch commands, use first token as exptime if (!safe_strtol(tokens[1].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } key_token++; exptime = realtime(exptime_int); } do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if (nkey > KEY_MAX_LENGTH) { fail_length = true; goto stop; } it = limited_get(key, nkey, c, exptime, should_touch); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (_ascii_get_expand_ilist(c, i) != 0) { item_remove(it); goto stop; } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); int nbytes; suffix = _ascii_get_suffix_buf(c, si); if (suffix == NULL) { item_remove(it); goto stop; } si++; nbytes = it->nbytes; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); goto stop; } #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { if (_get_extstore(c, it, c->iovused-3, 4) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); item_remove(it); goto stop; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { #else if ((it->it_flags & ITEM_CHUNKED) == 0) { #endif add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); goto stop; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.lru_hits[it->slabs_clsid]++; c->thread->stats.get_cmds++; } pthread_mutex_unlock(&c->thread->stats.mutex); #ifdef EXTSTORE /* If ITEM_HDR, an io_wrap owns the reference. */ if ((it->it_flags & ITEM_HDR) == 0) { *(c->ilist + i) = it; i++; } #else *(c->ilist + i) = it; i++; #endif } else { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_misses++; c->thread->stats.get_cmds++; } MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); pthread_mutex_unlock(&c->thread->stats.mutex); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); stop: c->icurr = c->ilist; c->ileft = i; c->suffixcurr = c->suffixlist; c->suffixleft = si; if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { if (fail_length) { out_string(c, "CLIENT_ERROR bad command line format"); } else { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } conn_release_items(c); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { char *key; size_t nkey; unsigned int flags; int32_t exptime_int = 0; time_t exptime; int vlen; uint64_t req_cas_id=0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags) && safe_strtol(tokens[3].value, &exptime_int) && safe_strtol(tokens[4].value, (int32_t *)&vlen))) { out_string(c, "CLIENT_ERROR bad command line format"); return; } /* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */ exptime = exptime_int; /* Negative exptimes can underflow and end up immortal. realtime() will immediately expire values that are greater than REALTIME_MAXDELTA, but less than process_started, so lets aim for that. */ if (exptime < 0) exptime = REALTIME_MAXDELTA + 1; // does cas value exist? if (handle_cas) { if (!safe_strtoull(tokens[5].value, &req_cas_id)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } if (vlen < 0 || vlen > (INT_MAX - 2)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } vlen += 2; if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, flags, realtime(exptime), vlen); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, flags, vlen)) { out_string(c, "SERVER_ERROR object too large for cache"); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR out of memory storing object"); status = NO_MEMORY; } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, comm, key, nkey, 0, 0, c->sfd); /* swallow the data line */ c->write_and_go = conn_swallow; c->sbytes = vlen; /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (comm == NREAD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } return; } ITEM_set_cas(it, req_cas_id); c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = it->nbytes; c->cmd = comm; conn_set_state(c, conn_nread); } static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; int32_t exptime_int = 0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtol(tokens[2].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } it = item_touch(key, nkey, realtime(exptime_int), c); if (it) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "TOUCHED"); item_remove(it); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) { char temp[INCR_MAX_STORAGE_LEN]; uint64_t delta; char *key; size_t nkey; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtoull(tokens[2].value, &delta)) { out_string(c, "CLIENT_ERROR invalid numeric delta argument"); return; } switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) { case OK: out_string(c, temp); break; case NON_NUMERIC: out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value"); break; case EOM: out_of_memory(c, "SERVER_ERROR out of memory"); break; case DELTA_ITEM_NOT_FOUND: pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); break; case DELTA_ITEM_CAS_MISMATCH: break; /* Should never get here */ } } /* * adds a delta value to a numeric item. * * c connection requesting the operation * it item to adjust * incr true to increment value, false to decrement * delta amount to adjust value by * buf buffer for response string * * returns a response string to send back to the client. */ enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, const bool incr, const int64_t delta, char *buf, uint64_t *cas, const uint32_t hv) { char *ptr; uint64_t value; int res; item *it; it = do_item_get(key, nkey, hv, c, DONT_UPDATE); if (!it) { return DELTA_ITEM_NOT_FOUND; } /* Can't delta zero byte values. 2-byte are the "\r\n" */ /* Also can't delta for chunked items. Too large to be a number */ #ifdef EXTSTORE if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) { #else if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) { #endif do_item_remove(it); return NON_NUMERIC; } if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { do_item_remove(it); return DELTA_ITEM_CAS_MISMATCH; } ptr = ITEM_data(it); if (!safe_strtoull(ptr, &value)) { do_item_remove(it); return NON_NUMERIC; } if (incr) { value += delta; MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); } else { if(delta > value) { value = 0; } else { value -= delta; } MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); } pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; } else { c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); itoa_u64(value, buf); res = strlen(buf); /* refcount == 2 means we are the only ones holding the item, and it is * linked. We hold the item's lock in this function, so refcount cannot * increase. */ if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ /* When changing the value without replacing the item, we need to update the CAS on the existing item. */ /* We also need to fiddle it in the sizes tracker in case the tracking * was enabled at runtime, since it relies on the CAS value to know * whether to remove an item or not. */ item_stats_sizes_remove(it); ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); item_stats_sizes_add(it); memcpy(ITEM_data(it), buf, res); memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); do_item_update(it); } else if (it->refcount > 1) { item *new_it; uint32_t flags; FLAGS_CONV(it, flags); new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); if (new_it == 0) { do_item_remove(it); return EOM; } memcpy(ITEM_data(new_it), buf, res); memcpy(ITEM_data(new_it) + res, "\r\n", 2); item_replace(it, new_it, hv); // Overwrite the older item's CAS with our new CAS since we're // returning the CAS of the old item below. ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); do_item_remove(new_it); /* release our reference */ } else { /* Should never get here. This means we somehow fetched an unlinked * item. TODO: Add a counter? */ if (settings.verbose) { fprintf(stderr, "Tried to do incr/decr on invalid item\n"); } if (it->refcount == 1) do_item_remove(it); return DELTA_ITEM_NOT_FOUND; } if (cas) { *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ } do_item_remove(it); /* release our reference */ return OK; } static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; item *it; uint32_t hv; assert(c != NULL); if (ntokens > 3) { bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0; bool sets_noreply = set_noreply_maybe(c, tokens, ntokens); bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply)) || (ntokens == 5 && hold_is_zero && sets_noreply); if (!valid) { out_string(c, "CLIENT_ERROR bad command line format. " "Usage: delete <key> [noreply]"); return; } } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); do_item_remove(it); /* release our reference */ out_string(c, "DELETED"); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } item_unlock(hv); } static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[1].value, NULL, 10); settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level; out_string(c, "OK"); return; } #ifdef MEMCACHED_DEBUG static void process_misbehave_command(conn *c) { int allowed = 0; // try opening new TCP socket int i = socket(AF_INET, SOCK_STREAM, 0); if (i != -1) { allowed++; close(i); } // try executing new commands i = system("sleep 0"); if (i != -1) { allowed++; } if (allowed) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; double ratio; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[2].value, "ratio") == 0) { if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) { out_string(c, "ERROR"); return; } settings.slab_automove_ratio = ratio; } else { level = strtoul(tokens[2].value, NULL, 10); if (level == 0) { settings.slab_automove = 0; } else if (level == 1 || level == 2) { settings.slab_automove = level; } else { out_string(c, "ERROR"); return; } } out_string(c, "OK"); return; } /* TODO: decide on syntax for sampling? */ static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) { uint16_t f = 0; int x; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (ntokens > 2) { for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) { if ((strcmp(tokens[x].value, "rawcmds") == 0)) { f |= LOG_RAWCMDS; } else if ((strcmp(tokens[x].value, "evictions") == 0)) { f |= LOG_EVICTIONS; } else if ((strcmp(tokens[x].value, "fetchers") == 0)) { f |= LOG_FETCHERS; } else if ((strcmp(tokens[x].value, "mutations") == 0)) { f |= LOG_MUTATIONS; } else if ((strcmp(tokens[x].value, "sysevents") == 0)) { f |= LOG_SYSEVENTS; } else { out_string(c, "ERROR"); return; } } } else { f |= LOG_FETCHERS; } switch(logger_add_watcher(c, c->sfd, f)) { case LOGGER_ADD_WATCHER_TOO_MANY: out_string(c, "WATCHER_TOO_MANY log watcher limit reached"); break; case LOGGER_ADD_WATCHER_FAILED: out_string(c, "WATCHER_FAILED failed to add log watcher"); break; case LOGGER_ADD_WATCHER_OK: conn_set_state(c, conn_watch); event_del(&c->event); break; } } static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t memlimit; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (!safe_strtoul(tokens[1].value, &memlimit)) { out_string(c, "ERROR"); } else { if (memlimit < 8) { out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m"); } else { if (memlimit > 1000000000) { out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes"); } else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) { if (settings.verbose > 0) { fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit); } out_string(c, "OK"); } else { out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust"); } } } } static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; double hot_factor; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtod(tokens[4].value, &hot_factor) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0 || hot_factor <= 0) { out_string(c, "ERROR hot/warm age factors must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_factor = hot_factor; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } #ifdef EXTSTORE static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) { set_noreply_maybe(c, tokens, ntokens); bool ok = true; if (ntokens < 4) { ok = false; } else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) { /* per-slab-class free chunk setting. */ unsigned int clsid = 0; unsigned int limit = 0; if (!safe_strtoul(tokens[2].value, &clsid) || !safe_strtoul(tokens[3].value, &limit)) { ok = false; } else { if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) { settings.ext_free_memchunks[clsid] = limit; } else { ok = false; } } } else if (strcmp(tokens[1].value, "item_size") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_size)) ok = false; } else if (strcmp(tokens[1].value, "item_age") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_age)) ok = false; } else if (strcmp(tokens[1].value, "low_ttl") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl)) ok = false; } else if (strcmp(tokens[1].value, "recache_rate") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate)) ok = false; } else if (strcmp(tokens[1].value, "compact_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under)) ok = false; } else if (strcmp(tokens[1].value, "drop_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under)) ok = false; } else if (strcmp(tokens[1].value, "max_frag") == 0) { if (!safe_strtod(tokens[2].value, &settings.ext_max_frag)) ok = false; } else if (strcmp(tokens[1].value, "drop_unread") == 0) { unsigned int v; if (!safe_strtoul(tokens[2].value, &v)) { ok = false; } else { settings.ext_drop_unread = v == 0 ? false : true; } } else { ok = false; } if (!ok) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_command(conn *c, char *command) { token_t tokens[MAX_TOKENS]; size_t ntokens; int comm; assert(c != NULL); MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); if (settings.verbose > 1) fprintf(stderr, "<%d %s\n", c->sfd, command); /* * for commands set/add/replace, we build an item and read the data * directly into it, then continue in nread_complete(). */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR out of memory preparing response"); return; } ntokens = tokenize_command(command, tokens, MAX_TOKENS); if (ntokens >= 3 && ((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) || (strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) { process_get_command(c, tokens, ntokens, false, false); } else if ((ntokens == 6 || ntokens == 7) && ((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) || (strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) || (strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) || (strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) || (strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) { process_update_command(c, tokens, ntokens, comm, false); } else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) { process_update_command(c, tokens, ntokens, comm, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 1); } else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) { process_get_command(c, tokens, ntokens, true, false); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 0); } else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) { process_delete_command(c, tokens, ntokens); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) { process_touch_command(c, tokens, ntokens); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) { process_get_command(c, tokens, ntokens, false, true); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) { process_get_command(c, tokens, ntokens, true, true); } else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) { process_stat(c, tokens, ntokens); } else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) { time_t exptime = 0; rel_time_t new_oldest = 0; set_noreply_maybe(c, tokens, ntokens); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats out_string(c, "CLIENT_ERROR flush_all not allowed"); return; } if (ntokens != (c->noreply ? 3 : 2)) { exptime = strtol(tokens[1].value, NULL, 10); if(errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } /* If exptime is zero realtime() would return zero too, and realtime(exptime) - 1 would overflow to the max unsigned value. So we process exptime == 0 the same way we do when no delay is given at all. */ if (exptime > 0) { new_oldest = realtime(exptime); } else { /* exptime == 0 */ new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } out_string(c, "OK"); return; } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) { out_string(c, "VERSION " VERSION); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) { conn_set_state(c, conn_closing); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) { if (settings.shutdown_command) { conn_set_state(c, conn_closing); raise(SIGINT); } else { out_string(c, "ERROR: shutdown not enabled"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) { if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) { int src, dst, rv; if (settings.slab_reassign == false) { out_string(c, "CLIENT_ERROR slab reassignment disabled"); return; } src = strtol(tokens[2].value, NULL, 10); dst = strtol(tokens[3].value, NULL, 10); if (errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } rv = slabs_reassign(src, dst); switch (rv) { case REASSIGN_OK: out_string(c, "OK"); break; case REASSIGN_RUNNING: out_string(c, "BUSY currently processing reassign request"); break; case REASSIGN_BADCLASS: out_string(c, "BADCLASS invalid src or dst class id"); break; case REASSIGN_NOSPARE: out_string(c, "NOSPARE source class has no spare pages"); break; case REASSIGN_SRC_DST_SAME: out_string(c, "SAME src and dst class are identical"); break; } return; } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) { process_slabs_automove_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) { if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) { int rv; if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0, settings.lru_crawler_tocrawl); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) { if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } if (!settings.dump_enabled) { out_string(c, "ERROR metadump not allowed"); return; } int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP, c, c->sfd, LRU_CRAWLER_CAP_REMAINING); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); // TODO: Don't reuse conn_watch here. conn_set_state(c, conn_watch); event_del(&c->event); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) { uint32_t tocrawl; if (!safe_strtoul(tokens[2].value, &tocrawl)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } settings.lru_crawler_tocrawl = tocrawl; out_string(c, "OK"); return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) { uint32_t tosleep; if (!safe_strtoul(tokens[2].value, &tosleep)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (tosleep > 1000000) { out_string(c, "CLIENT_ERROR sleep must be one second or less"); return; } settings.lru_crawler_sleep = tosleep; out_string(c, "OK"); return; } else if (ntokens == 3) { if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) { if (start_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to start lru crawler thread"); } } else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) { if (stop_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to stop lru crawler thread"); } } else { out_string(c, "ERROR"); } return; } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) { process_watch_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) { process_memlimit_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) { process_verbosity_command(c, tokens, ntokens); } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) { process_lru_command(c, tokens, ntokens); #ifdef MEMCACHED_DEBUG // commands which exist only for testing the memcached's security protection } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) { process_misbehave_command(c); #endif #ifdef EXTSTORE } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) { process_extstore_command(c, tokens, ntokens); #endif #ifdef TLS } else if (ntokens == 2 && strcmp(tokens[COMMAND_TOKEN].value, "refresh_certs") == 0) { set_noreply_maybe(c, tokens, ntokens); char *errmsg = NULL; if (refresh_certs(&errmsg)) { out_string(c, "OK"); } else { write_and_free(c, errmsg, strlen(errmsg)); } return; #endif } else { if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) { conn_set_state(c, conn_closing); } else { out_string(c, "ERROR"); } } return; } static int try_read_command_negotiate(conn *c) { assert(c->protocol == negotiating_prot); assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; c->try_read_command = try_read_command_binary; } else { // authentication doesn't work with negotiated protocol. c->protocol = ascii_prot; c->try_read_command = try_read_command_ascii; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } return c->try_read_command(c); } static int try_read_command_udp(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; return try_read_command_binary(c); } else { c->protocol = ascii_prot; return try_read_command_ascii(c); } } static int try_read_command_binary(conn *c) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR Out of memory allocating headers"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; c->last_cmd_time = current_time; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } return 1; } static int try_read_command_asciiauth(conn *c) { token_t tokens[MAX_TOKENS]; size_t ntokens; char *cont = NULL; // TODO: move to another function. if (!c->sasl_started) { char *el; uint32_t size = 0; // impossible for the auth command to be this short. if (c->rbytes < 2) return 0; el = memchr(c->rcurr, '\n', c->rbytes); // If no newline after 1k, getting junk data, close out. if (!el) { if (c->rbytes > 1024) { conn_set_state(c, conn_closing); return 1; } return 0; } // Looking for: "set foo 0 0 N\r\nuser pass\r\n" // key, flags, and ttl are ignored. N is used to see if we have the rest. // so tokenize doesn't walk past into the value. // it's fine to leave the \r in, as strtoul will stop at it. *el = '\0'; ntokens = tokenize_command(c->rcurr, tokens, MAX_TOKENS); // ensure the buffer is consumed. c->rbytes -= (el - c->rcurr) + 1; c->rcurr += (el - c->rcurr) + 1; // final token is a NULL ender, so we have one more than expected. if (ntokens < 6 || strcmp(tokens[0].value, "set") != 0 || !safe_strtoul(tokens[4].value, &size)) { out_string(c, "CLIENT_ERROR unauthenticated"); return 1; } // we don't actually care about the key at all; it can be anything. // we do care about the size of the remaining read. c->rlbytes = size + 2; c->sasl_started = true; // reuse from binprot sasl, but not sasl :) } if (c->rbytes < c->rlbytes) { // need more bytes. return 0; } cont = c->rcurr; // advance buffer. no matter what we're stopping. c->rbytes -= c->rlbytes; c->rcurr += c->rlbytes; c->sasl_started = false; // must end with \r\n // NB: I thought ASCII sets also worked with just \n, but according to // complete_nread_ascii only \r\n is valid. if (strncmp(cont + c->rlbytes - 2, "\r\n", 2) != 0) { out_string(c, "CLIENT_ERROR bad command line termination"); return 1; } // payload should be "user pass", so we can use the tokenizer. cont[c->rlbytes - 2] = '\0'; ntokens = tokenize_command(cont, tokens, MAX_TOKENS); if (ntokens < 3) { out_string(c, "CLIENT_ERROR bad authentication token format"); return 1; } if (authfile_check(tokens[0].value, tokens[1].value) == 1) { out_string(c, "STORED"); c->authenticated = true; c->try_read_command = try_read_command_ascii; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); } else { out_string(c, "CLIENT_ERROR authentication failure"); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } return 1; } static int try_read_command_ascii(conn *c) { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (ptr - c->rcurr > 100 || (strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); c->last_cmd_time = current_time; process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); return 1; } /* * read a UDP request. */ static enum try_read_result try_read_udp(conn *c) { int res; assert(c != NULL); c->request_addr_size = sizeof(c->request_addr); res = recvfrom(c->sfd, c->rbuf, c->rsize, 0, (struct sockaddr *)&c->request_addr, &c->request_addr_size); if (res > 8) { unsigned char *buf = (unsigned char *)c->rbuf; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* Beginning of UDP packet is the request ID; save it. */ c->request_id = buf[0] * 256 + buf[1]; /* If this is a multi-packet request, drop it. */ if (buf[4] != 0 || buf[5] != 1) { out_string(c, "SERVER_ERROR multi-packet request not supported"); return READ_NO_DATA_RECEIVED; } /* Don't care about any of the rest of the header. */ res -= 8; memmove(c->rbuf, c->rbuf + 8, res); c->rbytes = res; c->rcurr = c->rbuf; return READ_DATA_RECEIVED; } return READ_NO_DATA_RECEIVED; } /* * read from network as much as we can, handle buffer overflow and connection * close. * before reading, move the remaining incomplete fragment of a command * (if any) to the beginning of the buffer. * * To protect us from someone flooding a connection with bogus data causing * the connection to eat up all available memory, break out and start looking * at the data I've got after a number of reallocs... * * @return enum try_read_result */ static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose > 0) { fprintf(stderr, "Couldn't realloc input buffer\n"); } c->rbytes = 0; /* ignore what we read */ out_of_memory(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = c->read(c, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } static bool update_event(conn *c, const int new_flags) { assert(c != NULL); struct event_base *base = c->event.ev_base; if (c->ev_flags == new_flags) return true; if (event_del(&c->event) == -1) return false; event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = new_flags; if (event_add(&c->event, 0) == -1) return false; return true; } /* * Sets whether we are listening for new connections or not. */ void do_accept_new_conns(const bool do_accept) { conn *next; for (next = listen_conn; next; next = next->next) { if (do_accept) { update_event(next, EV_READ | EV_PERSIST); if (listen(next->sfd, settings.backlog) != 0) { perror("listen"); } } else { update_event(next, 0); if (listen(next->sfd, 0) != 0) { perror("listen"); } } } if (do_accept) { struct timeval maxconns_exited; uint64_t elapsed_us; gettimeofday(&maxconns_exited,NULL); STATS_LOCK(); elapsed_us = (maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000 + (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec); stats.time_in_listen_disabled_us += elapsed_us; stats_state.accepting_conns = true; STATS_UNLOCK(); } else { STATS_LOCK(); stats_state.accepting_conns = false; gettimeofday(&stats.maxconns_entered,NULL); stats.listen_disabled_num++; STATS_UNLOCK(); allow_new_conns = false; maxconns_handler(-42, 0, 0); } } /* * Transmit the next chunk of data from our list of msgbuf structures. * * Returns: * TRANSMIT_COMPLETE All done writing. * TRANSMIT_INCOMPLETE More data remaining to write. * TRANSMIT_SOFT_ERROR Can't write any more right now. * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing) */ static enum transmit_result transmit(conn *c) { assert(c != NULL); if (c->msgcurr < c->msgused && c->msglist[c->msgcurr].msg_iovlen == 0) { /* Finished writing the current msg; advance to the next. */ c->msgcurr++; } if (c->msgcurr < c->msgused) { ssize_t res; struct msghdr *m = &c->msglist[c->msgcurr]; res = c->sendmsg(c, m, 0); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_written += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* We've written some of the data. Remove the completed iovec entries from the list of pending writes. */ while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) { res -= m->msg_iov->iov_len; m->msg_iovlen--; m->msg_iov++; } /* Might have written just part of the last iovec entry; adjust it so the next write will do the rest. */ if (res > 0) { m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res; m->msg_iov->iov_len -= res; } return TRANSMIT_INCOMPLETE; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } return TRANSMIT_SOFT_ERROR; } /* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK, we have a real error, on which we close the connection */ if (settings.verbose > 0) perror("Failed to write, and not due to blocking"); if (IS_UDP(c->transport)) conn_set_state(c, conn_read); else conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } else { return TRANSMIT_COMPLETE; } } /* Does a looped read to fill data chunks */ /* TODO: restrict number of times this can loop. * Also, benchmark using readv's. */ static int read_into_chunked_item(conn *c) { int total = 0; int res; assert(c->rcurr != c->ritem); while (c->rlbytes > 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size == ch->used) { // FIXME: ch->next is currently always 0. remove this? if (ch->next) { c->ritem = (char *) ch->next; } else { /* Allocate next chunk. Binary protocol needs 2b for \r\n */ c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes + ((c->protocol == binary_prot) ? 2 : 0)); if (!c->ritem) { // We failed an allocation. Let caller handle cleanup. total = -2; break; } // ritem has new chunk, restart the loop. continue; //assert(c->rlbytes == 0); } } int unused = ch->size - ch->used; /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { total = 0; int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; tocopy = tocopy > unused ? unused : tocopy; if (c->ritem != c->rcurr) { memmove(ch->data + ch->used, c->rcurr, tocopy); } total += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; ch->used += tocopy; if (c->rlbytes == 0) { break; } } else { /* now try reading from the socket */ res = c->read(c, ch->data + ch->used, (unused > c->rlbytes ? c->rlbytes : unused)); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); ch->used += res; total += res; c->rlbytes -= res; } else { /* Reset total to the latest result so caller can handle it */ total = res; break; } } } /* At some point I will be able to ditch the \r\n from item storage and remove all of these kludges. The above binprot check ensures inline space for \r\n, but if we do exactly enough allocs there will be no additional chunk for \r\n. */ if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size - ch->used < 2) { c->ritem = (char *) do_item_alloc_chunk(ch, 2); if (!c->ritem) { total = -2; } } } return total; } static void drive_machine(conn *c) { bool stop = false; int sfd; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; #ifdef HAVE_ACCEPT4 static int use_accept4 = 1; #else static int use_accept4 = 0; #endif assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); #ifdef HAVE_ACCEPT4 if (use_accept4) { sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); } else { sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); } #else sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); #endif if (sfd == -1) { if (use_accept4 && errno == ENOSYS) { use_accept4 = 0; continue; } perror(use_accept4 ? "accept4()" : "accept()"); if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if (!use_accept4) { if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } } if (settings.maxconns_fast && stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { void *ssl_v = NULL; #ifdef TLS SSL *ssl = NULL; if (c->ssl_enabled) { assert(IS_TCP(c->transport) && settings.ssl_enabled); if (settings.ssl_ctx == NULL) { if (settings.verbose) { fprintf(stderr, "SSL context is not initialized\n"); } close(sfd); break; } SSL_LOCK(); ssl = SSL_new(settings.ssl_ctx); SSL_UNLOCK(); if (ssl == NULL) { if (settings.verbose) { fprintf(stderr, "Failed to created the SSL object\n"); } close(sfd); break; } SSL_set_fd(ssl, sfd); int ret = SSL_accept(ssl); if (ret < 0) { int err = SSL_get_error(ssl, ret); if (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) { if (settings.verbose) { fprintf(stderr, "SSL connection failed with error code : %d : %s\n", err, strerror(errno)); } close(sfd); break; } } } ssl_v = (void*) ssl; #endif dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, c->transport, ssl_v); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (c->try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* Check if rbytes < 0, to prevent crash */ if (c->rlbytes < 0) { if (settings.verbose) { fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes); } conn_set_state(c, conn_closing); break; } if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) { /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = c->read(c, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } } else { res = read_into_chunked_item(c); if (res > 0) break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* Memory allocation failure */ if (res == -2) { out_of_memory(c, "SERVER_ERROR Out of memory during read"); c->sbytes = c->rlbytes; c->write_and_go = conn_swallow; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes <= 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = c->read(c, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: #ifdef EXTSTORE /* have side IO's that must process before transmit() can run. * remove the connection from the worker thread and dispatch the * IO queue */ if (c->io_wrapleft) { assert(c->io_queued == false); assert(c->io_wraplist != NULL); // TODO: create proper state for this condition conn_set_state(c, conn_watch); event_del(&c->event); c->io_queued = true; extstore_submit(c->thread->storage, &c->io_wraplist->io); stop = true; break; } #endif if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { conn_release_items(c); /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_closed: /* This only happens if dormando is an idiot. */ abort(); break; case conn_watch: /* We handed off our connection to the logger thread. */ stop = true; break; case conn_max_state: assert(false); break; } } return; } void event_handler(const int fd, const short which, void *arg) { conn *c; c = (conn *)arg; assert(c != NULL); c->which = which; /* sanity */ if (fd != c->sfd) { if (settings.verbose > 0) fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n"); conn_close(c); return; } drive_machine(c); /* wait for next event */ return; } static int new_socket(struct addrinfo *ai) { int sfd; int flags; if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } /* * Sets a socket's send buffer size to the maximum allowed by the system. */ static void maximize_sndbuf(const int sfd) { socklen_t intsize = sizeof(int); int last_good = 0; int min, max, avg; int old_size; /* Start with the default size. */ if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) { if (settings.verbose > 0) perror("getsockopt(SO_SNDBUF)"); return; } /* Binary-search for the real maximum. */ min = old_size; max = MAX_SENDBUF_SIZE; while (min <= max) { avg = ((unsigned int)(min + max)) / 2; if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) { last_good = avg; min = avg + 1; } else { max = avg - 1; } } if (settings.verbose > 1) fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good); } /** * Create a socket and bind it to a specific port number * @param interface the interface to bind to * @param port the port number to bind to * @param transport the transport protocol (TCP / UDP) * @param portnumber_file A filepointer to write the port numbers to * when they are successfully added to the list of ports we * listen on. */ static int server_socket(const char *interface, int port, enum network_transport transport, FILE *portnumber_file, bool ssl_enabled) { int sfd; struct linger ling = {0, 0}; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; char port_buf[NI_MAXSERV]; int error; int success = 0; int flags =1; hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; if (port == -1) { port = 0; } snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { conn *listen_conn_add; if ((sfd = new_socket(next)) == -1) { /* getaddrinfo can return "junk" addresses, * we make sure at least one works before erroring. */ if (errno == EMFILE) { /* ...unless we're out of fds */ perror("server_socket"); exit(EX_OSERR); } continue; } #ifdef IPV6_V6ONLY if (next->ai_family == AF_INET6) { error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); if (error != 0) { perror("setsockopt"); close(sfd); continue; } } #endif setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (IS_UDP(transport)) { maximize_sndbuf(sfd); } else { error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); } if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } else { success++; if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); freeaddrinfo(ai); return 1; } if (portnumber_file != NULL && (next->ai_addr->sa_family == AF_INET || next->ai_addr->sa_family == AF_INET6)) { union { struct sockaddr_in in; struct sockaddr_in6 in6; } my_sockaddr; socklen_t len = sizeof(my_sockaddr); if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { if (next->ai_addr->sa_family == AF_INET) { fprintf(portnumber_file, "%s INET: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in.sin_port)); } else { fprintf(portnumber_file, "%s INET6: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in6.sin6_port)); } } } } if (IS_UDP(transport)) { int c; for (c = 0; c < settings.num_threads_per_udp; c++) { /* Allocate one UDP file descriptor per worker thread; * this allows "stats conns" to separately list multiple * parallel UDP requests in progress. * * The dispatch code round-robins new connection requests * among threads, so this is guaranteed to assign one * FD to each thread. */ int per_thread_fd; if (c == 0) { per_thread_fd = sfd; } else { per_thread_fd = dup(sfd); if (per_thread_fd < 0) { perror("Failed to duplicate file descriptor"); exit(EXIT_FAILURE); } } dispatch_conn_new(per_thread_fd, conn_read, EV_READ | EV_PERSIST, UDP_READ_BUFFER_SIZE, transport, NULL); } } else { if (!(listen_conn_add = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } #ifdef TLS listen_conn_add->ssl_enabled = ssl_enabled; #else assert(ssl_enabled == false); #endif listen_conn_add->next = listen_conn; listen_conn = listen_conn_add; } } freeaddrinfo(ai); /* Return zero iff we detected no errors in starting up connections */ return success == 0; } static int server_sockets(int port, enum network_transport transport, FILE *portnumber_file) { bool ssl_enabled = false; #ifdef TLS const char *notls = "notls"; ssl_enabled = settings.ssl_enabled; #endif if (settings.inter == NULL) { return server_socket(settings.inter, port, transport, portnumber_file, ssl_enabled); } else { // tokenize them and bind to each one of them.. char *b; int ret = 0; char *list = strdup(settings.inter); if (list == NULL) { fprintf(stderr, "Failed to allocate memory for parsing server interface string\n"); return 1; } for (char *p = strtok_r(list, ";,", &b); p != NULL; p = strtok_r(NULL, ";,", &b)) { int the_port = port; #ifdef TLS ssl_enabled = settings.ssl_enabled; // "notls" option is valid only when memcached is run with SSL enabled. if (strncmp(p, notls, strlen(notls)) == 0) { if (!settings.ssl_enabled) { fprintf(stderr, "'notls' option is valid only when SSL is enabled\n"); return 1; } ssl_enabled = false; p += strlen(notls) + 1; } #endif char *h = NULL; if (*p == '[') { // expecting it to be an IPv6 address enclosed in [] // i.e. RFC3986 style recommended by RFC5952 char *e = strchr(p, ']'); if (e == NULL) { fprintf(stderr, "Invalid IPV6 address: \"%s\"", p); free(list); return 1; } h = ++p; // skip the opening '[' *e = '\0'; p = ++e; // skip the closing ']' } char *s = strchr(p, ':'); if (s != NULL) { // If no more semicolons - attempt to treat as port number. // Otherwise the only valid option is an unenclosed IPv6 without port, until // of course there was an RFC3986 IPv6 address previously specified - // in such a case there is no good option, will just send it to fail as port number. if (strchr(s + 1, ':') == NULL || h != NULL) { *s = '\0'; ++s; if (!safe_strtol(s, &the_port)) { fprintf(stderr, "Invalid port number: \"%s\"", s); free(list); return 1; } } } if (h != NULL) p = h; if (strcmp(p, "*") == 0) { p = NULL; } ret |= server_socket(p, the_port, transport, portnumber_file, ssl_enabled); } free(list); return ret; } } static int new_socket_unix(void) { int sfd; int flags; if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } static int server_socket_unix(const char *path, int access_mask) { int sfd; struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags =1; int old_umask; if (!path) { return 1; } if ((sfd = new_socket_unix()) == -1) { return 1; } /* * Clean up a previous socket file if we left it around */ if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) unlink(path); } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); /* * the memset call clears nonstandard fields in some implementations * that otherwise mess things up. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask( ~(access_mask&0777)); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind()"); close(sfd); umask(old_umask); return 1; } umask(old_umask); if (listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); return 1; } if (!(listen_conn = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, local_transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } return 0; } /* * We keep the current time of day in a global variable that's updated by a * timer event. This saves us a bunch of time() system calls (we really only * need to get the time once a second, whereas there can be tens of thousands * of requests a second) and allows us to use server-start-relative timestamps * rather than absolute UNIX timestamps, a space savings on systems where * sizeof(time_t) > sizeof(unsigned int). */ volatile rel_time_t current_time; static struct event clockevent; /* libevent uses a monotonic clock when available for event scheduling. Aside * from jitter, simply ticking our internal timer here is accurate enough. * Note that users who are setting explicit dates for expiration times *must* * ensure their clocks are correct before starting memcached. */ static void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; static bool initialized = false; #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) static bool monotonic = false; static time_t monotonic_start; #endif if (initialized) { /* only delete the event if it's actually there. */ evtimer_del(&clockevent); } else { initialized = true; /* process_started is initialized to time() - 2. We initialize to 1 so * flush_all won't underflow during tests. */ #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { monotonic = true; monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2; } #endif } // While we're here, check for hash table expansion. // This function should be quick to avoid delaying the timer. assoc_start_expand(stats_state.curr_items); // also, if HUP'ed we need to do some maintenance. // for now that's just the authfile reload. if (settings.sig_hup) { settings.sig_hup = false; authfile_load(settings.auth_file); } evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) if (monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return; current_time = (rel_time_t) (ts.tv_sec - monotonic_start); return; } #endif { struct timeval tv; gettimeofday(&tv, NULL); current_time = (rel_time_t) (tv.tv_sec - process_started); } } static void usage(void) { printf(PACKAGE " " VERSION "\n"); printf("-p, --port=<num> TCP port to listen on (default: 11211)\n" "-U, --udp-port=<num> UDP port to listen on (default: 0, off)\n" "-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n" "-A, --enable-shutdown enable ascii \"shutdown\" command\n" "-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n" "-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n" #ifdef TLS " if TLS/SSL is enabled, 'notls' prefix can be used to\n" " disable for specific listeners (-l notls:<ip>:<port>) \n" #endif "-d, --daemon run as a daemon\n" "-r, --enable-coredumps maximize core file limit\n" "-u, --user=<user> assume identity of <username> (only when run as root)\n" "-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n" "-M, --disable-evictions return error on memory exhausted instead of evicting\n" "-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n" "-k, --lock-memory lock down all paged memory\n" "-v, --verbose verbose (print errors/warnings while in event loop)\n" "-vv very verbose (also print client commands/responses)\n" "-vvv extremely verbose (internal state transitions)\n" "-h, --help print this help and exit\n" "-i, --license print memcached and libevent license\n" "-V, --version print version and exit\n" "-P, --pidfile=<file> save PID in <file>, only used with -d option\n" "-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n" "-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n"); printf("-L, --enable-largepages try to use large memory pages (if available)\n"); printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n" " This is used for per-prefix stats reporting. The default is\n" " \":\" (colon). If this option is specified, stats collection\n" " is turned on automatically; if not, then it may be turned on\n" " by sending the \"stats detail on\" command to the server.\n"); printf("-t, --threads=<num> number of threads to use (default: 4)\n"); printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n" " requests processed per connection to prevent \n" " starvation (default: 20)\n"); printf("-C, --disable-cas disable use of CAS\n"); printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n"); printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n"); printf("-I, --max-item-size=<num> adjusts max item size\n" " (default: 1mb, min: 1k, max: 1024m)\n"); #ifdef ENABLE_SASL printf("-S, --enable-sasl turn on Sasl authentication\n"); #endif printf("-F, --disable-flush-all disable flush_all command\n"); printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n"); printf("-Y, --auth-file=<file> (EXPERIMENTAL) enable ASCII protocol authentication. format:\n" " user:pass\\nuser2:pass2\\n\n"); #ifdef TLS printf("-Z, --enable-ssl enable TLS/SSL\n"); #endif printf("-o, --extended comma separated list of extended options\n" " most options have a 'no_' prefix to disable\n" " - maxconns_fast: immediately close new connections after limit\n" " - hashpower: an integer multiplier for how large the hash\n" " table should be. normally grows at runtime.\n" " set based on \"STAT hash_power_level\"\n" " - tail_repair_time: time in seconds for how long to wait before\n" " forcefully killing LRU tail item.\n" " disabled by default; very dangerous option.\n" " - hash_algorithm: the hash table algorithm\n" " default is murmur3 hash. options: jenkins, murmur3\n" " - lru_crawler: enable LRU Crawler background thread\n" " - lru_crawler_sleep: microseconds to sleep between items\n" " default is 100.\n" " - lru_crawler_tocrawl: max items to crawl per slab per run\n" " default is 0 (unlimited)\n" " - lru_maintainer: enable new LRU system + background thread\n" " - hot_lru_pct: pct of slab memory to reserve for hot lru.\n" " (requires lru_maintainer)\n" " - warm_lru_pct: pct of slab memory to reserve for warm lru.\n" " (requires lru_maintainer)\n" " - hot_max_factor: items idle > cold lru age * drop from hot lru.\n" " - warm_max_factor: items idle > cold lru age * this drop from warm.\n" " - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n" " (requires lru_maintainer)\n" " - idle_timeout: timeout for idle connections\n" " - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n" " - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n" " - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n" " read by background thread, then written to watchers.\n" " - track_sizes: enable dynamic reports for 'stats sizes' command.\n" " - no_hashexpand: disables hash table expansion (dangerous)\n" " - modern: enables options which will be default in future.\n" " currently: nothing\n" " - no_modern: uses defaults of previous major version (1.4.x)\n" #ifdef HAVE_DROP_PRIVILEGES " - drop_privileges: enable dropping extra syscall privileges\n" " - no_drop_privileges: disable drop_privileges in case it causes issues with\n" " some customisation.\n" #ifdef MEMCACHED_DEBUG " - relaxed_privileges: Running tests requires extra privileges.\n" #endif #endif #ifdef EXTSTORE " - ext_path: file to write to for external storage.\n" " ie: ext_path=/mnt/d1/extstore:1G\n" " - ext_page_size: size in megabytes of storage pages.\n" " - ext_wbuf_size: size in megabytes of page write buffers.\n" " - ext_threads: number of IO threads to run.\n" " - ext_item_size: store items larger than this (bytes)\n" " - ext_item_age: store items idle at least this long\n" " - ext_low_ttl: consider TTLs lower than this specially\n" " - ext_drop_unread: don't re-write unread values during compaction\n" " - ext_recache_rate: recache an item every N accesses\n" " - ext_compact_under: compact when fewer than this many free pages\n" " - ext_drop_under: drop COLD items when fewer than this many free pages\n" " - ext_max_frag: max page fragmentation to tolerage\n" " - slab_automove_freeratio: ratio of memory to hold free as buffer.\n" " (see doc/storage.txt for more info)\n" #endif #ifdef TLS " - ssl_chain_cert: certificate chain file in PEM format\n" " - ssl_key: private key, if not part of the -ssl_chain_cert\n" " - ssl_keyformat: private key format (PEM, DER or ENGINE) PEM default\n" " - ssl_verify_mode: peer certificate verification mode, default is 0(None).\n" " valid values are 0(None), 1(Request), 2(Require)\n" " or 3(Once)\n" " - ssl_ciphers: specify cipher list to be used\n" " - ssl_ca_cert: PEM format file of acceptable client CA's\n" " - ssl_wbuf_size: size in kilobytes of per-connection SSL output buffer\n" #endif ); return; } static void usage_license(void) { printf(PACKAGE " " VERSION "\n\n"); printf( "Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are\n" "met:\n" "\n" " * Redistributions of source code must retain the above copyright\n" "notice, this list of conditions and the following disclaimer.\n" "\n" " * Redistributions in binary form must reproduce the above\n" "copyright notice, this list of conditions and the following disclaimer\n" "in the documentation and/or other materials provided with the\n" "distribution.\n" "\n" " * Neither the name of the Danga Interactive nor the names of its\n" "contributors may be used to endorse or promote products derived from\n" "this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" "\n" "\n" "This product includes software developed by Niels Provos.\n" "\n" "[ libevent ]\n" "\n" "Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions\n" "are met:\n" "1. Redistributions of source code must retain the above copyright\n" " notice, this list of conditions and the following disclaimer.\n" "2. Redistributions in binary form must reproduce the above copyright\n" " notice, this list of conditions and the following disclaimer in the\n" " documentation and/or other materials provided with the distribution.\n" "3. All advertising materials mentioning features or use of this software\n" " must display the following acknowledgement:\n" " This product includes software developed by Niels Provos.\n" "4. The name of the author may not be used to endorse or promote products\n" " derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ); return; } static void save_pid(const char *pid_file) { FILE *fp; if (access(pid_file, F_OK) == 0) { if ((fp = fopen(pid_file, "r")) != NULL) { char buffer[1024]; if (fgets(buffer, sizeof(buffer), fp) != NULL) { unsigned int pid; if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) { fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid); } } fclose(fp); } } /* Create the pid file first with a temporary name, then * atomically move the file to the real name to avoid a race with * another process opening the file to read the pid, but finding * it empty. */ char tmp_pid_file[1024]; snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file); if ((fp = fopen(tmp_pid_file, "w")) == NULL) { vperror("Could not open the pid file %s for writing", tmp_pid_file); return; } fprintf(fp,"%ld\n", (long)getpid()); if (fclose(fp) == -1) { vperror("Could not close the pid file %s", tmp_pid_file); } if (rename(tmp_pid_file, pid_file) != 0) { vperror("Could not rename the pid file from %s to %s", tmp_pid_file, pid_file); } } static void remove_pidfile(const char *pid_file) { if (pid_file == NULL) return; if (unlink(pid_file) != 0) { vperror("Could not remove the pid file %s", pid_file); } } static void sig_handler(const int sig) { printf("Signal handled: %s.\n", strsignal(sig)); exit(EXIT_SUCCESS); } static void sighup_handler(const int sig) { settings.sig_hup = true; } #ifndef HAVE_SIGIGNORE static int sigignore(int sig) { struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 }; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } #endif /* * On systems that supports multiple page sizes we may reduce the * number of TLB-misses by using the biggest available page size */ static int enable_large_pages(void) { #if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL) int ret = -1; size_t sizes[32]; int avail = getpagesizes(sizes, 32); if (avail != -1) { size_t max = sizes[0]; struct memcntl_mha arg = {0}; int ii; for (ii = 1; ii < avail; ++ii) { if (max < sizes[ii]) { max = sizes[ii]; } } arg.mha_flags = 0; arg.mha_pagesize = max; arg.mha_cmd = MHA_MAPSIZE_BSSBRK; if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) { fprintf(stderr, "Failed to set large pages: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } else { ret = 0; } } else { fprintf(stderr, "Failed to get supported pagesizes: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } return ret; #elif defined(__linux__) && defined(MADV_HUGEPAGE) /* check if transparent hugepages is compiled into the kernel */ struct stat st; int ret = stat("/sys/kernel/mm/transparent_hugepage/enabled", &st); if (ret || !(st.st_mode & S_IFREG)) { fprintf(stderr, "Transparent huge pages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #elif defined(__FreeBSD__) int spages; size_t spagesl = sizeof(spages); if (sysctlbyname("vm.pmap.pg_ps_enabled", &spages, &spagesl, NULL, 0) != 0) { fprintf(stderr, "Could not evaluate the presence of superpages features."); return -1; } if (spages != 1) { fprintf(stderr, "Superpages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #else return -1; #endif } /** * Do basic sanity check of the runtime environment * @return true if no errors found, false if we can't use this env */ static bool sanitycheck(void) { /* One of our biggest problems is old and bogus libevents */ const char *ever = event_get_version(); if (ever != NULL) { if (strncmp(ever, "1.", 2) == 0) { /* Require at least 1.3 (that's still a couple of years old) */ if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) { fprintf(stderr, "You are using libevent %s.\nPlease upgrade to" " a more recent version (1.3 or newer)\n", event_get_version()); return false; } } } return true; } static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) { char *b = NULL; uint32_t size = 0; int i = 0; uint32_t last_size = 0; if (strlen(s) < 1) return false; for (char *p = strtok_r(s, "-", &b); p != NULL; p = strtok_r(NULL, "-", &b)) { if (!safe_strtoul(p, &size) || size < settings.chunk_size || size > settings.slab_chunk_size_max) { fprintf(stderr, "slab size %u is out of valid range\n", size); return false; } if (last_size >= size) { fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size); return false; } if (size <= last_size + CHUNK_ALIGN_BYTES) { fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n", size, CHUNK_ALIGN_BYTES); return false; } slab_sizes[i++] = size; last_size = size; if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) { fprintf(stderr, "too many slab classes specified\n"); return false; } } slab_sizes[i] = 0; return true; } int main (int argc, char **argv) { int c; bool lock_memory = false; bool do_daemonize = false; bool preallocate = false; int maxcore = 0; char *username = NULL; char *pid_file = NULL; struct passwd *pw; struct rlimit rlim; char *buf; char unit = '\0'; int size_max = 0; int retval = EXIT_SUCCESS; bool protocol_specified = false; bool tcp_specified = false; bool udp_specified = false; bool start_lru_maintainer = true; bool start_lru_crawler = true; bool start_assoc_maint = true; enum hashfunc_type hash_type = MURMUR3_HASH; uint32_t tocrawl; uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES]; bool use_slab_sizes = false; char *slab_sizes_unparsed = NULL; bool slab_chunk_size_changed = false; #ifdef EXTSTORE void *storage = NULL; struct extstore_conf_file *storage_file = NULL; struct extstore_conf ext_cf; #endif char *subopts, *subopts_orig; char *subopts_value; enum { MAXCONNS_FAST = 0, HASHPOWER_INIT, NO_HASHEXPAND, SLAB_REASSIGN, SLAB_AUTOMOVE, SLAB_AUTOMOVE_RATIO, SLAB_AUTOMOVE_WINDOW, TAIL_REPAIR_TIME, HASH_ALGORITHM, LRU_CRAWLER, LRU_CRAWLER_SLEEP, LRU_CRAWLER_TOCRAWL, LRU_MAINTAINER, HOT_LRU_PCT, WARM_LRU_PCT, HOT_MAX_FACTOR, WARM_MAX_FACTOR, TEMPORARY_TTL, IDLE_TIMEOUT, WATCHER_LOGBUF_SIZE, WORKER_LOGBUF_SIZE, SLAB_SIZES, SLAB_CHUNK_MAX, TRACK_SIZES, NO_INLINE_ASCII_RESP, MODERN, NO_MODERN, NO_CHUNKED_ITEMS, NO_SLAB_REASSIGN, NO_SLAB_AUTOMOVE, NO_MAXCONNS_FAST, INLINE_ASCII_RESP, NO_LRU_CRAWLER, NO_LRU_MAINTAINER, NO_DROP_PRIVILEGES, DROP_PRIVILEGES, #ifdef TLS SSL_CERT, SSL_KEY, SSL_VERIFY_MODE, SSL_KEYFORM, SSL_CIPHERS, SSL_CA_CERT, SSL_WBUF_SIZE, #endif #ifdef MEMCACHED_DEBUG RELAXED_PRIVILEGES, #endif #ifdef EXTSTORE EXT_PAGE_SIZE, EXT_WBUF_SIZE, EXT_THREADS, EXT_IO_DEPTH, EXT_PATH, EXT_ITEM_SIZE, EXT_ITEM_AGE, EXT_LOW_TTL, EXT_RECACHE_RATE, EXT_COMPACT_UNDER, EXT_DROP_UNDER, EXT_MAX_FRAG, EXT_DROP_UNREAD, SLAB_AUTOMOVE_FREERATIO, #endif }; char *const subopts_tokens[] = { [MAXCONNS_FAST] = "maxconns_fast", [HASHPOWER_INIT] = "hashpower", [NO_HASHEXPAND] = "no_hashexpand", [SLAB_REASSIGN] = "slab_reassign", [SLAB_AUTOMOVE] = "slab_automove", [SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio", [SLAB_AUTOMOVE_WINDOW] = "slab_automove_window", [TAIL_REPAIR_TIME] = "tail_repair_time", [HASH_ALGORITHM] = "hash_algorithm", [LRU_CRAWLER] = "lru_crawler", [LRU_CRAWLER_SLEEP] = "lru_crawler_sleep", [LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl", [LRU_MAINTAINER] = "lru_maintainer", [HOT_LRU_PCT] = "hot_lru_pct", [WARM_LRU_PCT] = "warm_lru_pct", [HOT_MAX_FACTOR] = "hot_max_factor", [WARM_MAX_FACTOR] = "warm_max_factor", [TEMPORARY_TTL] = "temporary_ttl", [IDLE_TIMEOUT] = "idle_timeout", [WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size", [WORKER_LOGBUF_SIZE] = "worker_logbuf_size", [SLAB_SIZES] = "slab_sizes", [SLAB_CHUNK_MAX] = "slab_chunk_max", [TRACK_SIZES] = "track_sizes", [NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp", [MODERN] = "modern", [NO_MODERN] = "no_modern", [NO_CHUNKED_ITEMS] = "no_chunked_items", [NO_SLAB_REASSIGN] = "no_slab_reassign", [NO_SLAB_AUTOMOVE] = "no_slab_automove", [NO_MAXCONNS_FAST] = "no_maxconns_fast", [INLINE_ASCII_RESP] = "inline_ascii_resp", [NO_LRU_CRAWLER] = "no_lru_crawler", [NO_LRU_MAINTAINER] = "no_lru_maintainer", [NO_DROP_PRIVILEGES] = "no_drop_privileges", [DROP_PRIVILEGES] = "drop_privileges", #ifdef TLS [SSL_CERT] = "ssl_chain_cert", [SSL_KEY] = "ssl_key", [SSL_VERIFY_MODE] = "ssl_verify_mode", [SSL_KEYFORM] = "ssl_keyformat", [SSL_CIPHERS] = "ssl_ciphers", [SSL_CA_CERT] = "ssl_ca_cert", [SSL_WBUF_SIZE] = "ssl_wbuf_size", #endif #ifdef MEMCACHED_DEBUG [RELAXED_PRIVILEGES] = "relaxed_privileges", #endif #ifdef EXTSTORE [EXT_PAGE_SIZE] = "ext_page_size", [EXT_WBUF_SIZE] = "ext_wbuf_size", [EXT_THREADS] = "ext_threads", [EXT_IO_DEPTH] = "ext_io_depth", [EXT_PATH] = "ext_path", [EXT_ITEM_SIZE] = "ext_item_size", [EXT_ITEM_AGE] = "ext_item_age", [EXT_LOW_TTL] = "ext_low_ttl", [EXT_RECACHE_RATE] = "ext_recache_rate", [EXT_COMPACT_UNDER] = "ext_compact_under", [EXT_DROP_UNDER] = "ext_drop_under", [EXT_MAX_FRAG] = "ext_max_frag", [EXT_DROP_UNREAD] = "ext_drop_unread", [SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio", #endif NULL }; if (!sanitycheck()) { return EX_OSERR; } /* handle SIGINT, SIGTERM */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sighup_handler); /* init settings */ settings_init(); #ifdef EXTSTORE settings.ext_item_size = 512; settings.ext_item_age = UINT_MAX; settings.ext_low_ttl = 0; settings.ext_recache_rate = 2000; settings.ext_max_frag = 0.8; settings.ext_drop_unread = false; settings.ext_wbuf_size = 1024 * 1024 * 4; settings.ext_compact_under = 0; settings.ext_drop_under = 0; settings.slab_automove_freeratio = 0.01; ext_cf.page_size = 1024 * 1024 * 64; ext_cf.wbuf_size = settings.ext_wbuf_size; ext_cf.io_threadcount = 1; ext_cf.io_depth = 1; ext_cf.page_buckets = 4; ext_cf.wbuf_count = ext_cf.page_buckets; #endif /* Run regardless of initializing it later */ init_lru_maintainer(); /* set stderr non-buffering (for running under, say, daemontools) */ setbuf(stderr, NULL); char *shortopts = "a:" /* access mask for unix socket */ "A" /* enable admin shutdown command */ "Z" /* enable SSL */ "p:" /* TCP port number to listen on */ "s:" /* unix socket path to listen on */ "U:" /* UDP port number to listen on */ "m:" /* max memory to use for items in megabytes */ "M" /* return error on memory exhausted */ "c:" /* max simultaneous connections */ "k" /* lock down all paged memory */ "hiV" /* help, licence info, version */ "r" /* maximize core file limit */ "v" /* verbose */ "d" /* daemon mode */ "l:" /* interface to listen on */ "u:" /* user identity to run as */ "P:" /* save PID in file */ "f:" /* factor? */ "n:" /* minimum space allocated for key+value+flags */ "t:" /* threads */ "D:" /* prefix delimiter? */ "L" /* Large memory pages */ "R:" /* max requests per event */ "C" /* Disable use of CAS */ "b:" /* backlog queue limit */ "B:" /* Binding protocol */ "I:" /* Max item size */ "S" /* Sasl ON */ "F" /* Disable flush_all */ "X" /* Disable dump commands */ "Y:" /* Enable token auth */ "o:" /* Extended generic options */ ; /* process arguments */ #ifdef HAVE_GETOPT_LONG const struct option longopts[] = { {"unix-mask", required_argument, 0, 'a'}, {"enable-shutdown", no_argument, 0, 'A'}, {"enable-ssl", no_argument, 0, 'Z'}, {"port", required_argument, 0, 'p'}, {"unix-socket", required_argument, 0, 's'}, {"udp-port", required_argument, 0, 'U'}, {"memory-limit", required_argument, 0, 'm'}, {"disable-evictions", no_argument, 0, 'M'}, {"conn-limit", required_argument, 0, 'c'}, {"lock-memory", no_argument, 0, 'k'}, {"help", no_argument, 0, 'h'}, {"license", no_argument, 0, 'i'}, {"version", no_argument, 0, 'V'}, {"enable-coredumps", no_argument, 0, 'r'}, {"verbose", optional_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"listen", required_argument, 0, 'l'}, {"user", required_argument, 0, 'u'}, {"pidfile", required_argument, 0, 'P'}, {"slab-growth-factor", required_argument, 0, 'f'}, {"slab-min-size", required_argument, 0, 'n'}, {"threads", required_argument, 0, 't'}, {"enable-largepages", no_argument, 0, 'L'}, {"max-reqs-per-event", required_argument, 0, 'R'}, {"disable-cas", no_argument, 0, 'C'}, {"listen-backlog", required_argument, 0, 'b'}, {"protocol", required_argument, 0, 'B'}, {"max-item-size", required_argument, 0, 'I'}, {"enable-sasl", no_argument, 0, 'S'}, {"disable-flush-all", no_argument, 0, 'F'}, {"disable-dumping", no_argument, 0, 'X'}, {"auth-file", required_argument, 0, 'Y'}, {"extended", required_argument, 0, 'o'}, {0, 0, 0, 0} }; int optindex; while (-1 != (c = getopt_long(argc, argv, shortopts, longopts, &optindex))) { #else while (-1 != (c = getopt(argc, argv, shortopts))) { #endif switch (c) { case 'A': /* enables "shutdown" command */ settings.shutdown_command = true; break; case 'Z': /* enable secure communication*/ #ifdef TLS settings.ssl_enabled = true; #else fprintf(stderr, "This server is not built with TLS support.\n"); exit(EX_USAGE); #endif break; case 'a': /* access for unix domain socket, as octal mask (like chmod)*/ settings.access= strtol(optarg,NULL,8); break; case 'U': settings.udpport = atoi(optarg); udp_specified = true; break; case 'p': settings.port = atoi(optarg); tcp_specified = true; break; case 's': settings.socketpath = optarg; break; case 'm': settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024; break; case 'M': settings.evict_to_free = 0; break; case 'c': settings.maxconns = atoi(optarg); if (settings.maxconns <= 0) { fprintf(stderr, "Maximum connections must be greater than 0\n"); return 1; } break; case 'h': usage(); exit(EXIT_SUCCESS); case 'i': usage_license(); exit(EXIT_SUCCESS); case 'V': printf(PACKAGE " " VERSION "\n"); exit(EXIT_SUCCESS); case 'k': lock_memory = true; break; case 'v': settings.verbose++; break; case 'l': if (settings.inter != NULL) { if (strstr(settings.inter, optarg) != NULL) { break; } size_t len = strlen(settings.inter) + strlen(optarg) + 2; char *p = malloc(len); if (p == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } snprintf(p, len, "%s,%s", settings.inter, optarg); free(settings.inter); settings.inter = p; } else { settings.inter= strdup(optarg); } break; case 'd': do_daemonize = true; break; case 'r': maxcore = 1; break; case 'R': settings.reqs_per_event = atoi(optarg); if (settings.reqs_per_event == 0) { fprintf(stderr, "Number of requests per event must be greater than 0\n"); return 1; } break; case 'u': username = optarg; break; case 'P': pid_file = optarg; break; case 'f': settings.factor = atof(optarg); if (settings.factor <= 1.0) { fprintf(stderr, "Factor must be greater than 1\n"); return 1; } break; case 'n': settings.chunk_size = atoi(optarg); if (settings.chunk_size == 0) { fprintf(stderr, "Chunk size must be greater than 0\n"); return 1; } break; case 't': settings.num_threads = atoi(optarg); if (settings.num_threads <= 0) { fprintf(stderr, "Number of threads must be greater than 0\n"); return 1; } /* There're other problems when you get above 64 threads. * In the future we should portably detect # of cores for the * default. */ if (settings.num_threads > 64) { fprintf(stderr, "WARNING: Setting a high number of worker" "threads is not recommended.\n" " Set this value to the number of cores in" " your machine or less.\n"); } break; case 'D': if (! optarg || ! optarg[0]) { fprintf(stderr, "No delimiter specified\n"); return 1; } settings.prefix_delimiter = optarg[0]; settings.detail_enabled = 1; break; case 'L' : if (enable_large_pages() == 0) { preallocate = true; } else { fprintf(stderr, "Cannot enable large pages on this system\n" "(There is no support as of this version)\n"); return 1; } break; case 'C' : settings.use_cas = false; break; case 'b' : settings.backlog = atoi(optarg); break; case 'B': protocol_specified = true; if (strcmp(optarg, "auto") == 0) { settings.binding_protocol = negotiating_prot; } else if (strcmp(optarg, "binary") == 0) { settings.binding_protocol = binary_prot; } else if (strcmp(optarg, "ascii") == 0) { settings.binding_protocol = ascii_prot; } else { fprintf(stderr, "Invalid value for binding protocol: %s\n" " -- should be one of auto, binary, or ascii\n", optarg); exit(EX_USAGE); } break; case 'I': buf = strdup(optarg); unit = buf[strlen(buf)-1]; if (unit == 'k' || unit == 'm' || unit == 'K' || unit == 'M') { buf[strlen(buf)-1] = '\0'; size_max = atoi(buf); if (unit == 'k' || unit == 'K') size_max *= 1024; if (unit == 'm' || unit == 'M') size_max *= 1024 * 1024; settings.item_size_max = size_max; } else { settings.item_size_max = atoi(buf); } free(buf); break; case 'S': /* set Sasl authentication to true. Default is false */ #ifndef ENABLE_SASL fprintf(stderr, "This server is not built with SASL support.\n"); exit(EX_USAGE); #endif settings.sasl = true; break; case 'F' : settings.flush_enabled = false; break; case 'X' : settings.dump_enabled = false; break; case 'Y' : // dupe the file path now just in case the options get mangled. settings.auth_file = strdup(optarg); break; case 'o': /* It's sub-opts time! */ subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */ while (*subopts != '\0') { switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) { case MAXCONNS_FAST: settings.maxconns_fast = true; break; case HASHPOWER_INIT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for hashpower\n"); return 1; } settings.hashpower_init = atoi(subopts_value); if (settings.hashpower_init < 12) { fprintf(stderr, "Initial hashtable multiplier of %d is too low\n", settings.hashpower_init); return 1; } else if (settings.hashpower_init > 32) { fprintf(stderr, "Initial hashtable multiplier of %d is too high\n" "Choose a value based on \"STAT hash_power_level\" from a running instance\n", settings.hashpower_init); return 1; } break; case NO_HASHEXPAND: start_assoc_maint = false; break; case SLAB_REASSIGN: settings.slab_reassign = true; break; case SLAB_AUTOMOVE: if (subopts_value == NULL) { settings.slab_automove = 1; break; } settings.slab_automove = atoi(subopts_value); if (settings.slab_automove < 0 || settings.slab_automove > 2) { fprintf(stderr, "slab_automove must be between 0 and 2\n"); return 1; } break; case SLAB_AUTOMOVE_RATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_ratio argument\n"); return 1; } settings.slab_automove_ratio = atof(subopts_value); if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) { fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n"); return 1; } break; case SLAB_AUTOMOVE_WINDOW: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_window argument\n"); return 1; } settings.slab_automove_window = atoi(subopts_value); if (settings.slab_automove_window < 3) { fprintf(stderr, "slab_automove_window must be > 2\n"); return 1; } break; case TAIL_REPAIR_TIME: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for tail_repair_time\n"); return 1; } settings.tail_repair_time = atoi(subopts_value); if (settings.tail_repair_time < 10) { fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n"); return 1; } break; case HASH_ALGORITHM: if (subopts_value == NULL) { fprintf(stderr, "Missing hash_algorithm argument\n"); return 1; }; if (strcmp(subopts_value, "jenkins") == 0) { hash_type = JENKINS_HASH; } else if (strcmp(subopts_value, "murmur3") == 0) { hash_type = MURMUR3_HASH; } else { fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n"); return 1; } break; case LRU_CRAWLER: start_lru_crawler = true; break; case LRU_CRAWLER_SLEEP: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_sleep value\n"); return 1; } settings.lru_crawler_sleep = atoi(subopts_value); if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) { fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n"); return 1; } break; case LRU_CRAWLER_TOCRAWL: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_tocrawl value\n"); return 1; } if (!safe_strtoul(subopts_value, &tocrawl)) { fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n"); return 1; } settings.lru_crawler_tocrawl = tocrawl; break; case LRU_MAINTAINER: start_lru_maintainer = true; settings.lru_segmented = true; break; case HOT_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_lru_pct argument\n"); return 1; } settings.hot_lru_pct = atoi(subopts_value); if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) { fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n"); return 1; } break; case WARM_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_lru_pct argument\n"); return 1; } settings.warm_lru_pct = atoi(subopts_value); if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) { fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n"); return 1; } break; case HOT_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_max_factor argument\n"); return 1; } settings.hot_max_factor = atof(subopts_value); if (settings.hot_max_factor <= 0) { fprintf(stderr, "hot_max_factor must be > 0\n"); return 1; } break; case WARM_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_max_factor argument\n"); return 1; } settings.warm_max_factor = atof(subopts_value); if (settings.warm_max_factor <= 0) { fprintf(stderr, "warm_max_factor must be > 0\n"); return 1; } break; case TEMPORARY_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing temporary_ttl argument\n"); return 1; } settings.temp_lru = true; settings.temporary_ttl = atoi(subopts_value); break; case IDLE_TIMEOUT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for idle_timeout\n"); return 1; } settings.idle_timeout = atoi(subopts_value); break; case WATCHER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing watcher_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) { fprintf(stderr, "could not parse argument to watcher_logbuf_size\n"); return 1; } settings.logger_watcher_buf_size *= 1024; /* kilobytes */ break; case WORKER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing worker_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) { fprintf(stderr, "could not parse argument to worker_logbuf_size\n"); return 1; } settings.logger_buf_size *= 1024; /* kilobytes */ case SLAB_SIZES: slab_sizes_unparsed = strdup(subopts_value); break; case SLAB_CHUNK_MAX: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_chunk_max argument\n"); } if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) { fprintf(stderr, "could not parse argument to slab_chunk_max\n"); } slab_chunk_size_changed = true; break; case TRACK_SIZES: item_stats_sizes_init(); break; case NO_INLINE_ASCII_RESP: break; case INLINE_ASCII_RESP: break; case NO_CHUNKED_ITEMS: settings.slab_chunk_size_max = settings.slab_page_size; break; case NO_SLAB_REASSIGN: settings.slab_reassign = false; break; case NO_SLAB_AUTOMOVE: settings.slab_automove = 0; break; case NO_MAXCONNS_FAST: settings.maxconns_fast = false; break; case NO_LRU_CRAWLER: settings.lru_crawler = false; start_lru_crawler = false; break; case NO_LRU_MAINTAINER: start_lru_maintainer = false; settings.lru_segmented = false; break; #ifdef TLS case SSL_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_chain_cert argument\n"); return 1; } settings.ssl_chain_cert = strdup(subopts_value); break; case SSL_KEY: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_key argument\n"); return 1; } settings.ssl_key = strdup(subopts_value); break; case SSL_VERIFY_MODE: { if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_verify_mode argument\n"); return 1; } int verify = 0; if (!safe_strtol(subopts_value, &verify)) { fprintf(stderr, "could not parse argument to ssl_verify_mode\n"); return 1; } switch(verify) { case 0: settings.ssl_verify_mode = SSL_VERIFY_NONE; break; case 1: settings.ssl_verify_mode = SSL_VERIFY_PEER; break; case 2: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; break; case 3: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; break; default: fprintf(stderr, "Invalid ssl_verify_mode. Use help to see valid options.\n"); return 1; } break; } case SSL_KEYFORM: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_keyformat argument\n"); return 1; } if (!safe_strtol(subopts_value, &settings.ssl_keyformat)) { fprintf(stderr, "could not parse argument to ssl_keyformat\n"); return 1; } break; case SSL_CIPHERS: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ciphers argument\n"); return 1; } settings.ssl_ciphers = strdup(subopts_value); break; case SSL_CA_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ca_cert argument\n"); return 1; } settings.ssl_ca_cert = strdup(subopts_value); break; case SSL_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ssl_wbuf_size)) { fprintf(stderr, "could not parse argument to ssl_wbuf_size\n"); return 1; } settings.ssl_wbuf_size *= 1024; /* kilobytes */ break; #endif #ifdef EXTSTORE case EXT_PAGE_SIZE: if (storage_file) { fprintf(stderr, "Must specify ext_page_size before any ext_path arguments\n"); return 1; } if (subopts_value == NULL) { fprintf(stderr, "Missing ext_page_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.page_size)) { fprintf(stderr, "could not parse argument to ext_page_size\n"); return 1; } ext_cf.page_size *= 1024 * 1024; /* megabytes */ break; case EXT_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) { fprintf(stderr, "could not parse argument to ext_wbuf_size\n"); return 1; } ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */ settings.ext_wbuf_size = ext_cf.wbuf_size; break; case EXT_THREADS: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_threads argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) { fprintf(stderr, "could not parse argument to ext_threads\n"); return 1; } break; case EXT_IO_DEPTH: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_io_depth argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) { fprintf(stderr, "could not parse argument to ext_io_depth\n"); return 1; } break; case EXT_ITEM_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_size)) { fprintf(stderr, "could not parse argument to ext_item_size\n"); return 1; } break; case EXT_ITEM_AGE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_age argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_age)) { fprintf(stderr, "could not parse argument to ext_item_age\n"); return 1; } break; case EXT_LOW_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_low_ttl argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) { fprintf(stderr, "could not parse argument to ext_low_ttl\n"); return 1; } break; case EXT_RECACHE_RATE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_recache_rate argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) { fprintf(stderr, "could not parse argument to ext_recache_rate\n"); return 1; } break; case EXT_COMPACT_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_compact_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) { fprintf(stderr, "could not parse argument to ext_compact_under\n"); return 1; } break; case EXT_DROP_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_drop_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) { fprintf(stderr, "could not parse argument to ext_drop_under\n"); return 1; } break; case EXT_MAX_FRAG: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_max_frag argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.ext_max_frag)) { fprintf(stderr, "could not parse argument to ext_max_frag\n"); return 1; } break; case SLAB_AUTOMOVE_FREERATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_freeratio argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) { fprintf(stderr, "could not parse argument to slab_automove_freeratio\n"); return 1; } break; case EXT_DROP_UNREAD: settings.ext_drop_unread = true; break; case EXT_PATH: if (subopts_value) { struct extstore_conf_file *tmp = storage_conf_parse(subopts_value, ext_cf.page_size); if (tmp == NULL) { fprintf(stderr, "failed to parse ext_path argument\n"); return 1; } if (storage_file != NULL) { tmp->next = storage_file; } storage_file = tmp; } else { fprintf(stderr, "missing argument to ext_path, ie: ext_path=/d/file:5G\n"); return 1; } break; #endif case MODERN: /* currently no new defaults */ break; case NO_MODERN: if (!slab_chunk_size_changed) { settings.slab_chunk_size_max = settings.slab_page_size; } settings.slab_reassign = false; settings.slab_automove = 0; settings.maxconns_fast = false; settings.lru_segmented = false; hash_type = JENKINS_HASH; start_lru_crawler = false; start_lru_maintainer = false; break; case NO_DROP_PRIVILEGES: settings.drop_privileges = false; break; case DROP_PRIVILEGES: settings.drop_privileges = true; break; #ifdef MEMCACHED_DEBUG case RELAXED_PRIVILEGES: settings.relaxed_privileges = true; break; #endif default: printf("Illegal suboption \"%s\"\n", subopts_value); return 1; } } free(subopts_orig); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings.item_size_max < 1024) { fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n"); exit(EX_USAGE); } if (settings.item_size_max > (settings.maxbytes / 2)) { fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n"); exit(EX_USAGE); } if (settings.item_size_max > (1024 * 1024 * 1024)) { fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n"); exit(EX_USAGE); } if (settings.item_size_max > 1024 * 1024) { if (!slab_chunk_size_changed) { // Ideal new default is 16k, but needs stitching. settings.slab_chunk_size_max = settings.slab_page_size / 2; } } if (settings.slab_chunk_size_max > settings.item_size_max) { fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n", settings.slab_chunk_size_max, settings.item_size_max); exit(EX_USAGE); } if (settings.item_size_max % settings.slab_chunk_size_max != 0) { fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n", settings.item_size_max, settings.slab_chunk_size_max); exit(EX_USAGE); } if (settings.slab_page_size % settings.slab_chunk_size_max != 0) { fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n", settings.slab_chunk_size_max, settings.slab_page_size); exit(EX_USAGE); } #ifdef EXTSTORE if (storage_file) { if (settings.item_size_max > ext_cf.wbuf_size) { fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n", settings.item_size_max, ext_cf.wbuf_size); exit(EX_USAGE); } if (settings.udpport) { fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n"); exit(EX_USAGE); } } #endif // Reserve this for the new default. If factor size hasn't changed, use // new default. /*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) { settings.factor = 1.08; }*/ if (slab_sizes_unparsed != NULL) { if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) { use_slab_sizes = true; } else { exit(EX_USAGE); } } if (settings.hot_lru_pct + settings.warm_lru_pct > 80) { fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n"); exit(EX_USAGE); } if (settings.temp_lru && !start_lru_maintainer) { fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n"); exit(EX_USAGE); } if (hash_init(hash_type) != 0) { fprintf(stderr, "Failed to initialize hash_algorithm!\n"); exit(EX_USAGE); } /* * Use one workerthread to serve each UDP port if the user specified * multiple ports */ if (settings.inter != NULL && strchr(settings.inter, ',')) { settings.num_threads_per_udp = 1; } else { settings.num_threads_per_udp = settings.num_threads; } if (settings.sasl) { if (!protocol_specified) { settings.binding_protocol = binary_prot; } else { if (settings.binding_protocol != binary_prot) { fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n"); exit(EX_USAGE); } } } if (settings.auth_file) { if (!protocol_specified) { settings.binding_protocol = ascii_prot; } else { if (settings.binding_protocol != ascii_prot) { fprintf(stderr, "ERROR: You cannot allow the BINARY protocol while using ascii authentication tokens.\n"); exit(EX_USAGE); } } } if (udp_specified && settings.udpport != 0 && !tcp_specified) { settings.port = settings.udpport; } #ifdef TLS /* * Setup SSL if enabled */ if (settings.ssl_enabled) { if (!settings.port) { fprintf(stderr, "ERROR: You cannot enable SSL without a TCP port.\n"); exit(EX_USAGE); } // openssl init methods. SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); // Initiate the SSL context. ssl_init(); } #endif if (maxcore != 0) { struct rlimit rlim_new; /* * First try raising to infinity; if that fails, try bringing * the soft limit to the hard. */ if (getrlimit(RLIMIT_CORE, &rlim) == 0) { rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) { /* failed. try raising just to the old max */ rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max; (void)setrlimit(RLIMIT_CORE, &rlim_new); } } /* * getrlimit again to see what we ended up with. Only fail if * the soft limit ends up 0, because then no core files will be * created at all. */ if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) { fprintf(stderr, "failed to ensure corefile creation\n"); exit(EX_OSERR); } } /* * If needed, increase rlimits to allow as many connections * as needed. */ if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to getrlimit number of files\n"); exit(EX_OSERR); } else { rlim.rlim_cur = settings.maxconns; rlim.rlim_max = settings.maxconns; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n"); exit(EX_OSERR); } } /* lose root privileges if we have them */ if (getuid() == 0 || geteuid() == 0) { if (username == 0 || *username == '\0') { fprintf(stderr, "can't run as root without the -u switch\n"); exit(EX_USAGE); } if ((pw = getpwnam(username)) == 0) { fprintf(stderr, "can't find the user %s to switch to\n", username); exit(EX_NOUSER); } if (setgroups(0, NULL) < 0) { fprintf(stderr, "failed to drop supplementary groups\n"); exit(EX_OSERR); } if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { fprintf(stderr, "failed to assume identity of user %s\n", username); exit(EX_OSERR); } } /* Initialize Sasl if -S was specified */ if (settings.sasl) { init_sasl(); } /* daemonize if requested */ /* if we want to ensure our ability to dump core, don't chdir to / */ if (do_daemonize) { if (sigignore(SIGHUP) == -1) { perror("Failed to ignore SIGHUP"); } if (daemonize(maxcore, settings.verbose) == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } /* lock paged memory if needed */ if (lock_memory) { #ifdef HAVE_MLOCKALL int res = mlockall(MCL_CURRENT | MCL_FUTURE); if (res != 0) { fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n", strerror(errno)); } #else fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n"); #endif } /* initialize main thread libevent instance */ #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101 /* If libevent version is larger/equal to 2.0.2-alpha, use newer version */ struct event_config *ev_config; ev_config = event_config_new(); event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK); main_base = event_base_new_with_config(ev_config); event_config_free(ev_config); #else /* Otherwise, use older API */ main_base = event_init(); #endif /* Load initial auth file if required */ if (settings.auth_file) { if (settings.udpport) { fprintf(stderr, "Cannot use UDP with ascii authentication enabled (-U 0 to disable)\n"); exit(EX_USAGE); } switch (authfile_load(settings.auth_file)) { case AUTHFILE_MISSING: // fall through. case AUTHFILE_OPENFAIL: vperror("Could not open authfile [%s] for reading", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OOM: fprintf(stderr, "Out of memory reading password file: %s", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_MALFORMED: fprintf(stderr, "Authfile [%s] has a malformed entry. Should be 'user:password'", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OK: break; } } /* initialize other stuff */ logger_init(); stats_init(); assoc_init(settings.hashpower_init); conn_init(); slabs_init(settings.maxbytes, settings.factor, preallocate, use_slab_sizes ? slab_sizes : NULL); #ifdef EXTSTORE if (storage_file) { enum extstore_res eres; if (settings.ext_compact_under == 0) { settings.ext_compact_under = storage_file->page_count / 4; /* Only rescues non-COLD items if below this threshold */ settings.ext_drop_under = storage_file->page_count / 4; } crc32c_init(); /* Init free chunks to zero. */ for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) { settings.ext_free_memchunks[x] = 0; } storage = extstore_init(storage_file, &ext_cf, &eres); if (storage == NULL) { fprintf(stderr, "Failed to initialize external storage: %s\n", extstore_err(eres)); if (eres == EXTSTORE_INIT_OPEN_FAIL) { perror("extstore open"); } exit(EXIT_FAILURE); } ext_storage = storage; /* page mover algorithm for extstore needs memory prefilled */ slabs_prefill_global(); } #endif if (settings.drop_privileges) { setup_privilege_violations_handler(); } /* * ignore SIGPIPE signals; we can use errno == EPIPE if we * need that information */ if (sigignore(SIGPIPE) == -1) { perror("failed to ignore SIGPIPE; sigaction"); exit(EX_OSERR); } /* start up worker threads if MT mode */ #ifdef EXTSTORE slabs_set_storage(storage); memcached_thread_init(settings.num_threads, storage); init_lru_crawler(storage); #else memcached_thread_init(settings.num_threads, NULL); init_lru_crawler(NULL); #endif if (start_assoc_maint && start_assoc_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (start_lru_crawler && start_item_crawler_thread() != 0) { fprintf(stderr, "Failed to enable LRU crawler thread\n"); exit(EXIT_FAILURE); } #ifdef EXTSTORE if (storage && start_storage_compact_thread(storage) != 0) { fprintf(stderr, "Failed to start storage compaction thread\n"); exit(EXIT_FAILURE); } if (storage && start_storage_write_thread(storage) != 0) { fprintf(stderr, "Failed to start storage writer thread\n"); exit(EXIT_FAILURE); } if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) { #else if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) { #endif fprintf(stderr, "Failed to enable LRU maintainer thread\n"); return 1; } if (settings.slab_reassign && start_slab_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (settings.idle_timeout && start_conn_timeout_thread() == -1) { exit(EXIT_FAILURE); } /* initialise clock event */ clock_handler(0, 0, 0); /* create unix mode sockets after dropping privileges */ if (settings.socketpath != NULL) { errno = 0; if (server_socket_unix(settings.socketpath,settings.access)) { vperror("failed to listen on UNIX socket: %s", settings.socketpath); exit(EX_OSERR); } } /* create the listening socket, bind it, and init */ if (settings.socketpath == NULL) { const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME"); char *temp_portnumber_filename = NULL; size_t len; FILE *portnumber_file = NULL; if (portnumber_filename != NULL) { len = strlen(portnumber_filename)+4+1; temp_portnumber_filename = malloc(len); snprintf(temp_portnumber_filename, len, "%s.lck", portnumber_filename); portnumber_file = fopen(temp_portnumber_filename, "a"); if (portnumber_file == NULL) { fprintf(stderr, "Failed to open \"%s\": %s\n", temp_portnumber_filename, strerror(errno)); } } errno = 0; if (settings.port && server_sockets(settings.port, tcp_transport, portnumber_file)) { vperror("failed to listen on TCP port %d", settings.port); exit(EX_OSERR); } /* * initialization order: first create the listening sockets * (may need root on low ports), then drop root if needed, * then daemonize if needed, then init libevent (in some cases * descriptors created by libevent wouldn't survive forking). */ /* create the UDP listening socket and bind it */ errno = 0; if (settings.udpport && server_sockets(settings.udpport, udp_transport, portnumber_file)) { vperror("failed to listen on UDP port %d", settings.udpport); exit(EX_OSERR); } if (portnumber_file) { fclose(portnumber_file); rename(temp_portnumber_filename, portnumber_filename); } if (temp_portnumber_filename) free(temp_portnumber_filename); } /* Give the sockets a moment to open. I know this is dumb, but the error * is only an advisory. */ usleep(1000); if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n"); exit(EXIT_FAILURE); } if (pid_file != NULL) { save_pid(pid_file); } /* Drop privileges no longer needed */ if (settings.drop_privileges) { drop_privileges(); } /* Initialize the uriencode lookup table. */ uriencode_init(); /* enter the event loop */ if (event_base_loop(main_base, 0) != 0) { retval = EXIT_FAILURE; } stop_assoc_maintenance_thread(); /* remove the PID file if we're a daemon */ if (do_daemonize) remove_pidfile(pid_file); /* Clean up strdup() call for bind() address */ if (settings.inter) free(settings.inter); /* cleanup base */ event_base_free(main_base); return retval; }
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * memcached - memory caching daemon * * https://www.memcached.org/ * * Copyright 2003 Danga Interactive, Inc. All rights reserved. * * Use and distribution licensed under the BSD license. See * the LICENSE file for full text. * * Authors: * Anatoly Vorobey <mellon@pobox.com> * Brad Fitzpatrick <brad@danga.com> */ #include "memcached.h" #ifdef EXTSTORE #include "storage.h" #endif #include "authfile.h" #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/uio.h> #include <ctype.h> #include <stdarg.h> /* some POSIX systems need the following definition * to get mlockall flags out of sys/mman.h. */ #ifndef _P1003_1B_VISIBLE #define _P1003_1B_VISIBLE #endif /* need this to get IOV_MAX on some platforms. */ #ifndef __need_IOV_MAX #define __need_IOV_MAX #endif #include <pwd.h> #include <sys/mman.h> #include <fcntl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <assert.h> #include <limits.h> #include <sysexits.h> #include <stddef.h> #ifdef HAVE_GETOPT_LONG #include <getopt.h> #endif #ifdef TLS #include "tls.h" #endif #if defined(__FreeBSD__) #include <sys/sysctl.h> #endif /* FreeBSD 4.x doesn't have IOV_MAX exposed. */ #ifndef IOV_MAX #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__) # define IOV_MAX 1024 /* GNU/Hurd don't set MAXPATHLEN * http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */ #ifndef MAXPATHLEN #define MAXPATHLEN 4096 #endif #endif #endif /* * forward declarations */ static void drive_machine(conn *c); static int new_socket(struct addrinfo *ai); static ssize_t tcp_read(conn *arg, void *buf, size_t count); static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags); static ssize_t tcp_write(conn *arg, void *buf, size_t count); enum try_read_result { READ_DATA_RECEIVED, READ_NO_DATA_RECEIVED, READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */ READ_MEMORY_ERROR /** failed to allocate more memory */ }; static int try_read_command_negotiate(conn *c); static int try_read_command_udp(conn *c); static int try_read_command_binary(conn *c); static int try_read_command_ascii(conn *c); static int try_read_command_asciiauth(conn *c); static enum try_read_result try_read_network(conn *c); static enum try_read_result try_read_udp(conn *c); static void conn_set_state(conn *c, enum conn_states state); static int start_conn_timeout_thread(); /* stats */ static void stats_init(void); static void server_stats(ADD_STAT add_stats, conn *c); static void process_stat_settings(ADD_STAT add_stats, void *c); static void conn_to_str(const conn *c, char *addr, char *svr_addr); /** Return a datum for stats in binary protocol */ static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c); /* defaults */ static void settings_init(void); /* event handling, network IO */ static void event_handler(const int fd, const short which, void *arg); static void conn_close(conn *c); static void conn_init(void); static bool update_event(conn *c, const int new_flags); static void complete_nread(conn *c); static void process_command(conn *c, char *command); static void write_and_free(conn *c, char *buf, int bytes); static int ensure_iov_space(conn *c); static int add_iov(conn *c, const void *buf, int len); static int add_chunked_item_iovs(conn *c, item *it, int len); static int add_msghdr(conn *c); static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow); static void write_bin_miss_response(conn *c, char *key, size_t nkey); #ifdef EXTSTORE static void _get_extstore_cb(void *e, obj_io *io, int ret); static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt); #endif static void conn_free(conn *c); /** exported globals **/ struct stats stats; struct stats_state stats_state; struct settings settings; time_t process_started; /* when the process was started */ conn **conns; struct slab_rebalance slab_rebal; volatile int slab_rebalance_signal; #ifdef EXTSTORE /* hoping this is temporary; I'd prefer to cut globals, but will complete this * battle another day. */ void *ext_storage; #endif /** file scope variables **/ static conn *listen_conn = NULL; static int max_fds; static struct event_base *main_base; enum transmit_result { TRANSMIT_COMPLETE, /** All done writing. */ TRANSMIT_INCOMPLETE, /** More data remaining to write. */ TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */ TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */ }; /* Default methods to read from/ write to a socket */ ssize_t tcp_read(conn *c, void *buf, size_t count) { assert (c != NULL); return read(c->sfd, buf, count); } ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) { assert (c != NULL); return sendmsg(c->sfd, msg, flags); } ssize_t tcp_write(conn *c, void *buf, size_t count) { assert (c != NULL); return write(c->sfd, buf, count); } static enum transmit_result transmit(conn *c); /* This reduces the latency without adding lots of extra wiring to be able to * notify the listener thread of when to listen again. * Also, the clock timer could be broken out into its own thread and we * can block the listener via a condition. */ static volatile bool allow_new_conns = true; static struct event maxconnsevent; static void maxconns_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 0, .tv_usec = 10000}; if (fd == -42 || allow_new_conns == false) { /* reschedule in 10ms if we need to keep polling */ evtimer_set(&maxconnsevent, maxconns_handler, 0); event_base_set(main_base, &maxconnsevent); evtimer_add(&maxconnsevent, &t); } else { evtimer_del(&maxconnsevent); accept_new_conns(true); } } #define REALTIME_MAXDELTA 60*60*24*30 /* * given time value that's either unix time or delta from current unix time, return * unix time. Use the fact that delta can't exceed one month (and real time value can't * be that low). */ static rel_time_t realtime(const time_t exptime) { /* no. of seconds in 30 days - largest possible delta exptime */ if (exptime == 0) return 0; /* 0 means never expire */ if (exptime > REALTIME_MAXDELTA) { /* if item expiration is at/before the server started, give it an expiration time of 1 second after the server started. (because 0 means don't expire). without this, we'd underflow and wrap around to some large value way in the future, effectively making items expiring in the past really expiring never */ if (exptime <= process_started) return (rel_time_t)1; return (rel_time_t)(exptime - process_started); } else { return (rel_time_t)(exptime + current_time); } } static void stats_init(void) { memset(&stats, 0, sizeof(struct stats)); memset(&stats_state, 0, sizeof(struct stats_state)); stats_state.accepting_conns = true; /* assuming we start in this state. */ /* make the time we started always be 2 seconds before we really did, so time(0) - time.started is never zero. if so, things like 'settings.oldest_live' which act as booleans as well as values are now false in boolean context... */ process_started = time(0) - ITEM_UPDATE_INTERVAL - 2; stats_prefix_init(); } static void stats_reset(void) { STATS_LOCK(); memset(&stats, 0, sizeof(struct stats)); stats_prefix_clear(); STATS_UNLOCK(); threadlocal_stats_reset(); item_stats_reset(); } static void settings_init(void) { settings.use_cas = true; settings.access = 0700; settings.port = 11211; settings.udpport = 0; #ifdef TLS settings.ssl_enabled = false; settings.ssl_ctx = NULL; settings.ssl_chain_cert = NULL; settings.ssl_key = NULL; settings.ssl_verify_mode = SSL_VERIFY_NONE; settings.ssl_keyformat = SSL_FILETYPE_PEM; settings.ssl_ciphers = NULL; settings.ssl_ca_cert = NULL; settings.ssl_last_cert_refresh_time = current_time; settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB) #endif /* By default this string should be NULL for getaddrinfo() */ settings.inter = NULL; settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */ settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */ settings.verbose = 0; settings.oldest_live = 0; settings.oldest_cas = 0; /* supplements accuracy of oldest_live */ settings.evict_to_free = 1; /* push old items out of cache when memory runs out */ settings.socketpath = NULL; /* by default, not using a unix socket */ settings.auth_file = NULL; /* by default, not using ASCII authentication tokens */ settings.factor = 1.25; settings.chunk_size = 48; /* space for a modest key and value */ settings.num_threads = 4; /* N workers */ settings.num_threads_per_udp = 0; settings.prefix_delimiter = ':'; settings.detail_enabled = 0; settings.reqs_per_event = 20; settings.backlog = 1024; settings.binding_protocol = negotiating_prot; settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */ settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */ settings.slab_chunk_size_max = settings.slab_page_size / 2; settings.sasl = false; settings.maxconns_fast = true; settings.lru_crawler = false; settings.lru_crawler_sleep = 100; settings.lru_crawler_tocrawl = 0; settings.lru_maintainer_thread = false; settings.lru_segmented = true; settings.hot_lru_pct = 20; settings.warm_lru_pct = 40; settings.hot_max_factor = 0.2; settings.warm_max_factor = 2.0; settings.temp_lru = false; settings.temporary_ttl = 61; settings.idle_timeout = 0; /* disabled */ settings.hashpower_init = 0; settings.slab_reassign = true; settings.slab_automove = 1; settings.slab_automove_ratio = 0.8; settings.slab_automove_window = 30; settings.shutdown_command = false; settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT; settings.flush_enabled = true; settings.dump_enabled = true; settings.crawls_persleep = 1000; settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE; settings.logger_buf_size = LOGGER_BUF_SIZE; settings.drop_privileges = false; #ifdef MEMCACHED_DEBUG settings.relaxed_privileges = false; #endif } /* * Adds a message header to a connection. * * Returns 0 on success, -1 on out-of-memory. */ static int add_msghdr(conn *c) { struct msghdr *msg; assert(c != NULL); if (c->msgsize == c->msgused) { msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr)); if (! msg) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->msglist = msg; c->msgsize *= 2; } msg = c->msglist + c->msgused; /* this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the last 3 of which aren't defined on solaris: */ memset(msg, 0, sizeof(struct msghdr)); msg->msg_iov = &c->iov[c->iovused]; if (IS_UDP(c->transport) && c->request_addr_size > 0) { msg->msg_name = &c->request_addr; msg->msg_namelen = c->request_addr_size; } c->msgbytes = 0; c->msgused++; if (IS_UDP(c->transport)) { /* Leave room for the UDP header, which we'll fill in later. */ return add_iov(c, NULL, UDP_HEADER_SIZE); } return 0; } extern pthread_mutex_t conn_lock; /* Connection timeout thread bits */ static pthread_t conn_timeout_tid; #define CONNS_PER_SLICE 100 #define TIMEOUT_MSG_SIZE (1 + sizeof(int)) static void *conn_timeout_thread(void *arg) { int i; conn *c; char buf[TIMEOUT_MSG_SIZE]; rel_time_t oldest_last_cmd; int sleep_time; useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE); while(1) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread at top of connection list\n"); oldest_last_cmd = current_time; for (i = 0; i < max_fds; i++) { if ((i % CONNS_PER_SLICE) == 0) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread sleeping for %ulus\n", (unsigned int)timeslice); usleep(timeslice); } if (!conns[i]) continue; c = conns[i]; if (!IS_TCP(c->transport)) continue; if (c->state != conn_new_cmd && c->state != conn_read) continue; if ((current_time - c->last_cmd_time) > settings.idle_timeout) { buf[0] = 't'; memcpy(&buf[1], &i, sizeof(int)); if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE) != TIMEOUT_MSG_SIZE) perror("Failed to write timeout to notify pipe"); } else { if (c->last_cmd_time < oldest_last_cmd) oldest_last_cmd = c->last_cmd_time; } } /* This is the soonest we could have another connection time out */ sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1; if (sleep_time <= 0) sleep_time = 1; if (settings.verbose > 2) fprintf(stderr, "idle timeout thread finished pass, sleeping for %ds\n", sleep_time); usleep((useconds_t) sleep_time * 1000000); } return NULL; } static int start_conn_timeout_thread() { int ret; if (settings.idle_timeout == 0) return -1; if ((ret = pthread_create(&conn_timeout_tid, NULL, conn_timeout_thread, NULL)) != 0) { fprintf(stderr, "Can't create idle connection timeout thread: %s\n", strerror(ret)); return -1; } return 0; } /* * Initializes the connections array. We don't actually allocate connection * structures until they're needed, so as to avoid wasting memory when the * maximum connection count is much higher than the actual number of * connections. * * This does end up wasting a few pointers' worth of memory for FDs that are * used for things other than connections, but that's worth it in exchange for * being able to directly index the conns array by FD. */ static void conn_init(void) { /* We're unlikely to see an FD much higher than maxconns. */ int next_fd = dup(1); if (next_fd < 0) { perror("Failed to duplicate file descriptor\n"); exit(1); } int headroom = 10; /* account for extra unexpected open FDs */ struct rlimit rl; max_fds = settings.maxconns + headroom + next_fd; /* But if possible, get the actual highest FD we can possibly ever see. */ if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { max_fds = rl.rlim_max; } else { fprintf(stderr, "Failed to query maximum file descriptor; " "falling back to maxconns\n"); } close(next_fd); if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) { fprintf(stderr, "Failed to allocate connection structures\n"); /* This is unrecoverable so bail out early. */ exit(1); } } static const char *prot_text(enum protocol prot) { char *rv = "unknown"; switch(prot) { case ascii_prot: rv = "ascii"; break; case binary_prot: rv = "binary"; break; case negotiating_prot: rv = "auto-negotiate"; break; } return rv; } void conn_close_idle(conn *c) { if (settings.idle_timeout > 0 && (current_time - c->last_cmd_time) > settings.idle_timeout) { if (c->state != conn_new_cmd && c->state != conn_read) { if (settings.verbose > 1) fprintf(stderr, "fd %d wants to timeout, but isn't in read state", c->sfd); return; } if (settings.verbose > 1) fprintf(stderr, "Closing idle fd %d\n", c->sfd); c->thread->stats.idle_kicks++; conn_set_state(c, conn_closing); drive_machine(c); } } /* bring conn back from a sidethread. could have had its event base moved. */ void conn_worker_readd(conn *c) { c->ev_flags = EV_READ | EV_PERSIST; event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c); event_base_set(c->thread->base, &c->event); c->state = conn_new_cmd; // TODO: call conn_cleanup/fail/etc if (event_add(&c->event, 0) == -1) { perror("event_add"); } #ifdef EXTSTORE // If we had IO objects, process if (c->io_wraplist) { //assert(c->io_wrapleft == 0); // assert no more to process conn_set_state(c, conn_mwrite); drive_machine(c); } #endif } conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base, void *ssl) { conn *c; assert(sfd >= 0 && sfd < max_fds); c = conns[sfd]; if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->read = NULL; c->sendmsg = NULL; c->write = NULL; c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats_state.conn_structs++; STATS_UNLOCK(); c->sfd = sfd; conns[sfd] = c; } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (transport == tcp_transport && init_state == conn_new_cmd) { if (getpeername(sfd, (struct sockaddr *) &c->request_addr, &c->request_addr_size)) { perror("getpeername"); memset(&c->request_addr, 0, sizeof(c->request_addr)); } } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } #ifdef TLS c->ssl = NULL; c->ssl_wbuf = NULL; c->ssl_enabled = false; #endif c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->sasl_started = false; c->last_cmd_time = current_time; /* initialize for idle kicker */ #ifdef EXTSTORE c->io_wraplist = NULL; c->io_wrapleft = 0; #endif c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; #ifdef TLS if (ssl) { c->ssl = (SSL*)ssl; c->read = ssl_read; c->sendmsg = ssl_sendmsg; c->write = ssl_write; c->ssl_enabled = true; SSL_set_info_callback(c->ssl, ssl_callback); } else #else // This must be NULL if TLS is not enabled. assert(ssl == NULL); #endif { c->read = tcp_read; c->sendmsg = tcp_sendmsg; c->write = tcp_write; } if (IS_UDP(transport)) { c->try_read_command = try_read_command_udp; } else { switch (c->protocol) { case ascii_prot: if (settings.auth_file == NULL) { c->authenticated = true; c->try_read_command = try_read_command_ascii; } else { c->authenticated = false; c->try_read_command = try_read_command_asciiauth; } break; case binary_prot: // binprot handles its own authentication via SASL parsing. c->authenticated = false; c->try_read_command = try_read_command_binary; break; case negotiating_prot: c->try_read_command = try_read_command_negotiate; break; } } event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { perror("event_add"); return NULL; } STATS_LOCK(); stats_state.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } #ifdef EXTSTORE static void recache_or_free(conn *c, io_wrap *wrap) { item *it; it = (item *)wrap->io.buf; bool do_free = true; if (wrap->active) { // If request never dispatched, free the read buffer but leave the // item header alone. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); c->io_wrapleft--; assert(c->io_wrapleft >= 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_aborted_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (wrap->miss) { // If request was ultimately a miss, unlink the header. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); item_unlink(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.miss_from_extstore++; if (wrap->badcrc) c->thread->stats.badcrc_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (settings.ext_recache_rate) { // hashvalue is cuddled during store uint32_t hv = (uint32_t)it->time; // opt to throw away rather than wait on a lock. void *hold_lock = item_trylock(hv); if (hold_lock != NULL) { item *h_it = wrap->hdr_it; uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE; // Item must be recently hit at least twice to recache. if (((h_it->it_flags & flags) == flags) && h_it->time > current_time - ITEM_UPDATE_INTERVAL && c->recache_counter++ % settings.ext_recache_rate == 0) { do_free = false; // In case it's been updated. it->exptime = h_it->exptime; it->it_flags &= ~ITEM_LINKED; it->refcount = 0; it->h_next = NULL; // might not be necessary. STORAGE_delete(c->thread->storage, h_it); item_replace(h_it, it, hv); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.recache_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } } if (hold_lock) item_trylock_unlock(hold_lock); } if (do_free) slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it)); wrap->io.buf = NULL; // sanity. wrap->io.next = NULL; wrap->next = NULL; wrap->active = false; // TODO: reuse lock and/or hv. item_remove(wrap->hdr_it); } #endif static void conn_release_items(conn *c) { assert(c != NULL); if (c->item) { item_remove(c->item); c->item = 0; } while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } if (c->suffixleft != 0) { for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) { do_cache_free(c->thread->suffix_cache, *(c->suffixcurr)); } } #ifdef EXTSTORE if (c->io_wraplist) { io_wrap *tmp = c->io_wraplist; while (tmp) { io_wrap *next = tmp->next; recache_or_free(c, tmp); do_cache_free(c->thread->io_cache, tmp); // lockless tmp = next; } c->io_wraplist = NULL; } #endif c->icurr = c->ilist; c->suffixcurr = c->suffixlist; } static void conn_cleanup(conn *c) { assert(c != NULL); conn_release_items(c); if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } if (c->sasl_conn) { assert(settings.sasl); sasl_dispose(&c->sasl_conn); c->sasl_conn = NULL; } if (IS_UDP(c->transport)) { conn_set_state(c, conn_read); } } /* * Frees a connection. */ void conn_free(conn *c) { if (c) { assert(c != NULL); assert(c->sfd >= 0 && c->sfd < max_fds); MEMCACHED_CONN_DESTROY(c); conns[c->sfd] = NULL; if (c->hdrbuf) free(c->hdrbuf); if (c->msglist) free(c->msglist); if (c->rbuf) free(c->rbuf); if (c->wbuf) free(c->wbuf); if (c->ilist) free(c->ilist); if (c->suffixlist) free(c->suffixlist); if (c->iov) free(c->iov); #ifdef TLS if (c->ssl_wbuf) c->ssl_wbuf = NULL; #endif free(c); } } static void conn_close(conn *c) { assert(c != NULL); /* delete the event, the socket and the conn */ event_del(&c->event); if (settings.verbose > 1) fprintf(stderr, "<%d connection closed.\n", c->sfd); conn_cleanup(c); MEMCACHED_CONN_RELEASE(c->sfd); conn_set_state(c, conn_closed); #ifdef TLS if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); } #endif close(c->sfd); pthread_mutex_lock(&conn_lock); allow_new_conns = true; pthread_mutex_unlock(&conn_lock); STATS_LOCK(); stats_state.curr_conns--; STATS_UNLOCK(); return; } /* * Shrinks a connection's buffers if they're too big. This prevents * periodic large "get" requests from permanently chewing lots of server * memory. * * This should only be called in between requests since it can wipe output * buffers! */ static void conn_shrink(conn *c) { assert(c != NULL); if (IS_UDP(c->transport)) return; if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) { char *newbuf; if (c->rcurr != c->rbuf) memmove(c->rbuf, c->rcurr, (size_t)c->rbytes); newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE); if (newbuf) { c->rbuf = newbuf; c->rsize = DATA_BUFFER_SIZE; } /* TODO check other branch... */ c->rcurr = c->rbuf; } if (c->isize > ITEM_LIST_HIGHWAT) { item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0])); if (newbuf) { c->ilist = newbuf; c->isize = ITEM_LIST_INITIAL; } /* TODO check error condition? */ } if (c->msgsize > MSG_LIST_HIGHWAT) { struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0])); if (newbuf) { c->msglist = newbuf; c->msgsize = MSG_LIST_INITIAL; } /* TODO check error condition? */ } if (c->iovsize > IOV_LIST_HIGHWAT) { struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0])); if (newbuf) { c->iov = newbuf; c->iovsize = IOV_LIST_INITIAL; } /* TODO check return value */ } } /** * Convert a state name to a human readable form. */ static const char *state_text(enum conn_states state) { const char* const statenames[] = { "conn_listening", "conn_new_cmd", "conn_waiting", "conn_read", "conn_parse_cmd", "conn_write", "conn_nread", "conn_swallow", "conn_closing", "conn_mwrite", "conn_closed", "conn_watch" }; return statenames[state]; } /* * Sets a connection's current state in the state machine. Any special * processing that needs to happen on certain state transitions can * happen here. */ static void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state >= conn_listening && state < conn_max_state); if (state != c->state) { if (settings.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } if (state == conn_write || state == conn_mwrite) { MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes); } c->state = state; } } /* * Ensures that there is room for another struct iovec in a connection's * iov list. * * Returns 0 on success, -1 on out-of-memory. */ static int ensure_iov_space(conn *c) { assert(c != NULL); if (c->iovused >= c->iovsize) { int i, iovnum; struct iovec *new_iov = (struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec)); if (! new_iov) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->iov = new_iov; c->iovsize *= 2; /* Point all the msghdr structures at the new list. */ for (i = 0, iovnum = 0; i < c->msgused; i++) { c->msglist[i].msg_iov = &c->iov[iovnum]; iovnum += c->msglist[i].msg_iovlen; } } return 0; } /* * Adds data to the list of pending data that will be written out to a * connection. * * Returns 0 on success, -1 on out-of-memory. * Note: This is a hot path for at least ASCII protocol. While there is * redundant code in splitting TCP/UDP handling, any reduction in steps has a * large impact for TCP connections. */ static int add_iov(conn *c, const void *buf, int len) { struct msghdr *m; int leftover; assert(c != NULL); if (IS_UDP(c->transport)) { do { m = &c->msglist[c->msgused - 1]; /* * Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes. */ /* We may need to start a new msghdr if this one is full. */ if (m->msg_iovlen == IOV_MAX || (c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; /* If the fragment is too big to fit in the datagram, split it up */ if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) { leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE; len -= leftover; } else { leftover = 0; } m = &c->msglist[c->msgused - 1]; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; buf = ((char *)buf) + len; len = leftover; } while (leftover > 0); } else { /* Optimized path for TCP connections */ m = &c->msglist[c->msgused - 1]; if (m->msg_iovlen == IOV_MAX) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; } return 0; } static int add_chunked_item_iovs(conn *c, item *it, int len) { assert(it->it_flags & ITEM_CHUNKED); item_chunk *ch = (item_chunk *) ITEM_schunk(it); while (ch) { int todo = (len > ch->used) ? ch->used : len; if (add_iov(c, ch->data, todo) != 0) { return -1; } ch = ch->next; len -= todo; } return 0; } /* * Constructs a set of UDP headers and attaches them to the outgoing messages. */ static int build_udp_headers(conn *c) { int i; unsigned char *hdr; assert(c != NULL); if (c->msgused > c->hdrsize) { void *new_hdrbuf; if (c->hdrbuf) { new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE); } else { new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE); } if (! new_hdrbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->hdrbuf = (unsigned char *)new_hdrbuf; c->hdrsize = c->msgused * 2; } hdr = c->hdrbuf; for (i = 0; i < c->msgused; i++) { c->msglist[i].msg_iov[0].iov_base = (void*)hdr; c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE; *hdr++ = c->request_id / 256; *hdr++ = c->request_id % 256; *hdr++ = i / 256; *hdr++ = i % 256; *hdr++ = c->msgused / 256; *hdr++ = c->msgused % 256; *hdr++ = 0; *hdr++ = 0; assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE); } return 0; } static void out_string(conn *c, const char *str) { size_t len; assert(c != NULL); if (c->noreply) { if (settings.verbose > 1) fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str); c->noreply = false; conn_set_state(c, conn_new_cmd); return; } if (settings.verbose > 1) fprintf(stderr, ">%d %s\n", c->sfd, str); /* Nuke a partial output... */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; add_msghdr(c); len = strlen(str); if ((len + 2) > c->wsize) { /* ought to be always enough. just fail for simplicity */ str = "SERVER_ERROR output line too long"; len = strlen(str); } memcpy(c->wbuf, str, len); memcpy(c->wbuf + len, "\r\n", 2); c->wbytes = len + 2; c->wcurr = c->wbuf; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; return; } /* * Outputs a protocol-specific "out of memory" error. For ASCII clients, * this is equivalent to out_string(). */ static void out_of_memory(conn *c, char *ascii_error) { const static char error_prefix[] = "SERVER_ERROR "; const static int error_prefix_len = sizeof(error_prefix) - 1; if (c->protocol == binary_prot) { /* Strip off the generic error prefix; it's irrelevant in binary */ if (!strncmp(ascii_error, error_prefix, error_prefix_len)) { ascii_error += error_prefix_len; } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0); } else { out_string(c, ascii_error); } } /* * we get here after reading the value in set/add/replace commands. The command * has been stored in c->cmd, and the item is ready in c->item. */ static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } /** * get a pointer to the start of the request struct for the current command */ static void* binary_get_request(conn *c) { char *ret = c->rcurr; ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen + c->binary_header.request.extlen); assert(ret >= c->rbuf); return ret; } /** * get a pointer to the key in this request */ static char* binary_get_key(conn *c) { return c->rcurr - (c->binary_header.request.keylen); } static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) { protocol_binary_response_header* header; assert(c); c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { /* This should never run out of memory because iov and msg lists * have minimum sizes big enough to hold an error response. */ out_of_memory(c, "SERVER_ERROR out of memory adding binary header"); return; } header = (protocol_binary_response_header *)c->wbuf; header->response.magic = (uint8_t)PROTOCOL_BINARY_RES; header->response.opcode = c->binary_header.request.opcode; header->response.keylen = (uint16_t)htons(key_len); header->response.extlen = (uint8_t)hdr_len; header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES; header->response.status = (uint16_t)htons(err); header->response.bodylen = htonl(body_len); header->response.opaque = c->opaque; header->response.cas = htonll(c->cas); if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d Writing bin response:", c->sfd); for (ii = 0; ii < sizeof(header->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n>%d ", c->sfd); } fprintf(stderr, " 0x%02x", header->bytes[ii]); } fprintf(stderr, "\n"); } add_iov(c, c->wbuf, sizeof(header->response)); } /** * Writes a binary error response. If errstr is supplied, it is used as the * error text; otherwise a generic description of the error status code is * included. */ static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow) { size_t len; if (!errstr) { switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } /* Form and send a response to a command over the binary protocol */ static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) { if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET || c->cmd == PROTOCOL_BINARY_CMD_GETK) { add_bin_header(c, 0, hlen, keylen, dlen); if(dlen > 0) { add_iov(c, d, dlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { conn_set_state(c, conn_new_cmd); } } static void complete_incr_bin(conn *c) { item *it; char *key; size_t nkey; /* Weird magic in add_delta forces me to pad here */ char tmpbuf[INCR_MAX_STORAGE_LEN]; uint64_t cas = 0; protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf; protocol_binary_request_incr* req = binary_get_request(c); assert(c != NULL); assert(c->wsize >= sizeof(*rsp)); /* fix byteorder in the request */ req->message.body.delta = ntohll(req->message.body.delta); req->message.body.initial = ntohll(req->message.body.initial); req->message.body.expiration = ntohl(req->message.body.expiration); key = binary_get_key(c); nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int i; fprintf(stderr, "incr "); for (i = 0; i < nkey; i++) { fprintf(stderr, "%c", key[i]); } fprintf(stderr, " %lld, %llu, %d\n", (long long)req->message.body.delta, (long long)req->message.body.initial, req->message.body.expiration); } if (c->binary_header.request.cas != 0) { cas = c->binary_header.request.cas; } switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT, req->message.body.delta, tmpbuf, &cas)) { case OK: rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10)); if (cas) { c->cas = cas; } write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); break; case NON_NUMERIC: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0); break; case EOM: out_of_memory(c, "SERVER_ERROR Out of memory incrementing value"); break; case DELTA_ITEM_NOT_FOUND: if (req->message.body.expiration != 0xffffffff) { /* Save some room for the response */ rsp->message.body.value = htonll(req->message.body.initial); snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)req->message.body.initial); int res = strlen(tmpbuf); it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration), res + 2); if (it != NULL) { memcpy(ITEM_data(it), tmpbuf, res); memcpy(ITEM_data(it) + res, "\r\n", 2); if (store_item(it, NREAD_ADD, c)) { c->cas = ITEM_get_cas(it); write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, NULL, 0); } item_remove(it); /* release our reference */ } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating new item"); } } else { pthread_mutex_lock(&c->thread->stats.mutex); if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } break; case DELTA_ITEM_CAS_MISMATCH: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; } } static void complete_update_bin(conn *c) { protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL; enum store_item_type ret = NOT_STORED; assert(c != NULL); item *it = c->item; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); /* We don't actually receive the trailing two characters in the bin * protocol, so we're going to just set them here */ if ((it->it_flags & ITEM_CHUNKED) == 0) { *(ITEM_data(it) + it->nbytes - 2) = '\r'; *(ITEM_data(it) + it->nbytes - 1) = '\n'; } else { assert(c->ritem); item_chunk *ch = (item_chunk *) c->ritem; if (ch->size == ch->used) ch = ch->next; assert(ch->size - ch->used >= 2); ch->data[ch->used] = '\r'; ch->data[ch->used + 1] = '\n'; ch->used += 2; } ret = store_item(it, c->cmd, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; } #endif switch (ret) { case STORED: /* Stored */ write_bin_response(c, NULL, 0, 0, 0); break; case EXISTS: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; case NOT_FOUND: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); break; case NOT_STORED: case TOO_LARGE: case NO_MEMORY: if (c->cmd == NREAD_ADD) { eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } else if(c->cmd == NREAD_REPLACE) { eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED; } write_bin_error(c, eno, NULL, 0); } item_remove(c->item); /* release the c->item reference */ c->item = 0; } static void write_bin_miss_response(conn *c, char *key, size_t nkey) { if (nkey) { char *ofs = c->wbuf + sizeof(protocol_binary_response_header); add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0, nkey, nkey); memcpy(ofs, key, nkey); add_iov(c, ofs, nkey); conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } } static void process_bin_get_or_touch(conn *c) { item *it; protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf; char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH || c->cmd == PROTOCOL_BINARY_CMD_GAT || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH); bool failed = false; if (settings.verbose > 1) { fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET"); if (fwrite(key, 1, nkey, stderr)) {} fputc('\n', stderr); } if (should_touch) { protocol_binary_request_touch *t = binary_get_request(c); time_t exptime = ntohl(t->message.body.expiration); it = item_touch(key, nkey, realtime(exptime), c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it) { /* the length has two unnecessary bytes ("\r\n") */ uint16_t keylen = 0; uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2); pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.get_cmds++; c->thread->stats.lru_hits[it->slabs_clsid]++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) { bodylen -= it->nbytes - 2; } else if (should_return_key) { bodylen += nkey; keylen = nkey; } add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen); rsp->message.header.response.cas = htonll(ITEM_get_cas(it)); // add the flags FLAGS_CONV(it, rsp->message.body.flags); rsp->message.body.flags = htonl(rsp->message.body.flags); add_iov(c, &rsp->message.body, sizeof(rsp->message.body)); if (should_return_key) { add_iov(c, ITEM_key(it), nkey); } if (should_return_value) { /* Add the data minus the CRLF */ #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { int iovcnt = 4; int iovst = c->iovused - 3; if (!should_return_key) { iovcnt = 3; iovst = c->iovused - 2; } if (_get_extstore(c, it, iovst, iovcnt) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); failed = true; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #endif } if (!failed) { conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; /* Remember this command so we can garbage collect it later */ #ifdef EXTSTORE if ((it->it_flags & ITEM_HDR) != 0 && should_return_value) { // Only have extstore clean if header and returning value. c->item = NULL; } else { c->item = it; } #else c->item = it; #endif } else { item_remove(it); } } else { failed = true; } if (failed) { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_cmds++; c->thread->stats.get_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0); } else { MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } if (c->noreply) { conn_set_state(c, conn_new_cmd); } else { if (should_return_key) { write_bin_miss_response(c, key, nkey); } else { write_bin_miss_response(c, NULL, 0); } } } if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } } static void append_bin_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *buf = c->stats.buffer + c->stats.offset; uint32_t bodylen = klen + vlen; protocol_binary_response_header header = { .response.magic = (uint8_t)PROTOCOL_BINARY_RES, .response.opcode = PROTOCOL_BINARY_CMD_STAT, .response.keylen = (uint16_t)htons(klen), .response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES, .response.bodylen = htonl(bodylen), .response.opaque = c->opaque }; memcpy(buf, header.bytes, sizeof(header.response)); buf += sizeof(header.response); if (klen > 0) { memcpy(buf, key, klen); buf += klen; if (vlen > 0) { memcpy(buf, val, vlen); } } c->stats.offset += sizeof(header.response) + bodylen; } static void append_ascii_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *pos = c->stats.buffer + c->stats.offset; uint32_t nbytes = 0; int remaining = c->stats.size - c->stats.offset; int room = remaining - 1; if (klen == 0 && vlen == 0) { nbytes = snprintf(pos, room, "END\r\n"); } else if (vlen == 0) { nbytes = snprintf(pos, room, "STAT %s\r\n", key); } else { nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val); } c->stats.offset += nbytes; } static bool grow_stats_buf(conn *c, size_t needed) { size_t nsize = c->stats.size; size_t available = nsize - c->stats.offset; bool rv = true; /* Special case: No buffer -- need to allocate fresh */ if (c->stats.buffer == NULL) { nsize = 1024; available = c->stats.size = c->stats.offset = 0; } while (needed > available) { assert(nsize > 0); nsize = nsize << 1; available = nsize - c->stats.offset; } if (nsize != c->stats.size) { char *ptr = realloc(c->stats.buffer, nsize); if (ptr) { c->stats.buffer = ptr; c->stats.size = nsize; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); rv = false; } } return rv; } static void append_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, const void *cookie) { /* value without a key is invalid */ if (klen == 0 && vlen > 0) { return ; } conn *c = (conn*)cookie; if (c->protocol == binary_prot) { size_t needed = vlen + klen + sizeof(protocol_binary_response_header); if (!grow_stats_buf(c, needed)) { return ; } append_bin_stats(key, klen, val, vlen, c); } else { size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n" if (!grow_stats_buf(c, needed)) { return ; } append_ascii_stats(key, klen, val, vlen, c); } assert(c->stats.offset <= c->stats.size); } static void process_bin_stat(conn *c) { char *subcommand = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int ii; fprintf(stderr, "<%d STATS ", c->sfd); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", subcommand[ii]); } fprintf(stderr, "\n"); } if (nkey == 0) { /* request all statistics */ server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strncmp(subcommand, "reset", 5) == 0) { stats_reset(); } else if (strncmp(subcommand, "settings", 8) == 0) { process_stat_settings(&append_stats, c); } else if (strncmp(subcommand, "detail", 6) == 0) { char *subcmd_pos = subcommand + 6; if (strncmp(subcmd_pos, " dump", 5) == 0) { int len; char *dump_buf = stats_prefix_dump(&len); if (dump_buf == NULL || len <= 0) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); if (dump_buf != NULL) free(dump_buf); return; } else { append_stats("detailed", strlen("detailed"), dump_buf, len, c); free(dump_buf); } } else if (strncmp(subcmd_pos, " on", 3) == 0) { settings.detail_enabled = 1; } else if (strncmp(subcmd_pos, " off", 4) == 0) { settings.detail_enabled = 0; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); return; } } else { if (get_stats(subcommand, nkey, &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } return; } /* Append termination package and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) { assert(c); c->substate = next_substate; c->rlbytes = c->keylen + extra; /* Ok... do we have room for the extras and the key in the input buffer? */ ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf; if (c->rlbytes > c->rsize - offset) { size_t nsize = c->rsize; size_t size = c->rlbytes + sizeof(protocol_binary_request_header); while (size > nsize) { nsize *= 2; } if (nsize != c->rsize) { if (settings.verbose > 1) { fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n", c->sfd, (unsigned long)c->rsize, (unsigned long)nsize); } char *newm = realloc(c->rbuf, nsize); if (newm == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose) { fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n", c->sfd); } conn_set_state(c, conn_closing); return; } c->rbuf= newm; /* rcurr should point to the same offset in the packet */ c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header); c->rsize = nsize; } if (c->rbuf != c->rcurr) { memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Repack input buffer\n", c->sfd); } } } /* preserve the header in the buffer.. */ c->ritem = c->rcurr + sizeof(protocol_binary_request_header); conn_set_state(c, conn_nread); } /* Just write an error message and disconnect the client */ static void handle_binary_protocol_error(conn *c) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0); if (settings.verbose) { fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n", c->binary_header.request.opcode, c->sfd); } c->write_and_go = conn_closing; } static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; c->authenticated = false; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } static void bin_list_sasl_mechs(conn *c) { // Guard against a disabled SASL. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } init_sasl_conn(c); const char *result_string = NULL; unsigned int string_length = 0; int result=sasl_listmech(c->sasl_conn, NULL, "", /* What to prepend the string with */ " ", /* What to separate mechanisms with */ "", /* What to append to the string */ &result_string, &string_length, NULL); if (result != SASL_OK) { /* Perhaps there's a better error for this... */ if (settings.verbose) { fprintf(stderr, "Failed to list SASL mechanisms.\n"); } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } write_bin_response(c, (char*)result_string, 0, 0, string_length); } static void process_bin_sasl_auth(conn *c) { // Guard for handling disabled SASL on the server. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } assert(c->binary_header.request.extlen == 0); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > MAX_SASL_MECH_LEN) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; return; } char *key = binary_get_key(c); assert(key); item *it = item_alloc(key, nkey, 0, 0, vlen+2); /* Can't use a chunked item for SASL authentication. */ if (it == 0 || (it->it_flags & ITEM_CHUNKED)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen); c->write_and_go = conn_swallow; return; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_reading_sasl_auth_data; } static void process_bin_complete_sasl_auth(conn *c) { assert(settings.sasl); const char *out = NULL; unsigned int outlen = 0; assert(c->item); init_sasl_conn(c); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > ((item*) c->item)->nkey) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } char mech[nkey+1]; memcpy(mech, ITEM_key((item*)c->item), nkey); mech[nkey] = 0x00; if (settings.verbose) fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen); const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item); if (vlen > ((item*) c->item)->nbytes) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } int result=-1; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_AUTH: result = sasl_server_start(c->sasl_conn, mech, challenge, vlen, &out, &outlen); c->sasl_started = (result == SASL_OK || result == SASL_CONTINUE); break; case PROTOCOL_BINARY_CMD_SASL_STEP: if (!c->sasl_started) { if (settings.verbose) { fprintf(stderr, "%d: SASL_STEP called but sasl_server_start " "not called for this connection!\n", c->sfd); } break; } result = sasl_server_step(c->sasl_conn, challenge, vlen, &out, &outlen); break; default: assert(false); /* CMD should be one of the above */ /* This code is pretty much impossible, but makes the compiler happier */ if (settings.verbose) { fprintf(stderr, "Unhandled command %d with challenge %s\n", c->cmd, challenge); } break; } item_unlink(c->item); if (settings.verbose) { fprintf(stderr, "sasl result code: %d\n", result); } switch(result) { case SASL_OK: c->authenticated = true; write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated")); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); break; case SASL_CONTINUE: add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen); if(outlen > 0) { add_iov(c, out, outlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; break; default: if (settings.verbose) fprintf(stderr, "Unknown sasl response: %d\n", result); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: rv = c->authenticated; } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } static void dispatch_bin_command(conn *c) { int protocol_error = 0; uint8_t extlen = c->binary_header.request.extlen; uint16_t keylen = c->binary_header.request.keylen; uint32_t bodylen = c->binary_header.request.bodylen; if (keylen > bodylen || keylen + extlen > bodylen) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0); c->write_and_go = conn_closing; return; } if (settings.sasl && !authenticated(c)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); c->write_and_go = conn_closing; return; } MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); c->noreply = true; /* binprot supports 16bit keys, but internals are still 8bit */ if (keylen > KEY_MAX_LENGTH) { handle_binary_protocol_error(c); return; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_SETQ: c->cmd = PROTOCOL_BINARY_CMD_SET; break; case PROTOCOL_BINARY_CMD_ADDQ: c->cmd = PROTOCOL_BINARY_CMD_ADD; break; case PROTOCOL_BINARY_CMD_REPLACEQ: c->cmd = PROTOCOL_BINARY_CMD_REPLACE; break; case PROTOCOL_BINARY_CMD_DELETEQ: c->cmd = PROTOCOL_BINARY_CMD_DELETE; break; case PROTOCOL_BINARY_CMD_INCREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_INCREMENT; break; case PROTOCOL_BINARY_CMD_DECREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_DECREMENT; break; case PROTOCOL_BINARY_CMD_QUITQ: c->cmd = PROTOCOL_BINARY_CMD_QUIT; break; case PROTOCOL_BINARY_CMD_FLUSHQ: c->cmd = PROTOCOL_BINARY_CMD_FLUSH; break; case PROTOCOL_BINARY_CMD_APPENDQ: c->cmd = PROTOCOL_BINARY_CMD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPENDQ: c->cmd = PROTOCOL_BINARY_CMD_PREPEND; break; case PROTOCOL_BINARY_CMD_GETQ: c->cmd = PROTOCOL_BINARY_CMD_GET; break; case PROTOCOL_BINARY_CMD_GETKQ: c->cmd = PROTOCOL_BINARY_CMD_GETK; break; case PROTOCOL_BINARY_CMD_GATQ: c->cmd = PROTOCOL_BINARY_CMD_GAT; break; case PROTOCOL_BINARY_CMD_GATKQ: c->cmd = PROTOCOL_BINARY_CMD_GATK; break; default: c->noreply = false; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_VERSION: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, VERSION, 0, 0, strlen(VERSION)); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_FLUSH: if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) { bin_read_key(c, bin_read_flush_exptime, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_NOOP: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_REPLACE: if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) { bin_read_key(c, bin_reading_set_header, 8); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETK: if (extlen == 0 && bodylen == keylen && keylen > 0) { bin_read_key(c, bin_reading_get_key, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_DELETE: if (keylen > 0 && extlen == 0 && bodylen == keylen) { bin_read_key(c, bin_reading_del_header, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_INCREMENT: case PROTOCOL_BINARY_CMD_DECREMENT: if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) { bin_read_key(c, bin_reading_incr_header, 20); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_APPEND: case PROTOCOL_BINARY_CMD_PREPEND: if (keylen > 0 && extlen == 0) { bin_read_key(c, bin_reading_set_header, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_STAT: if (extlen == 0) { bin_read_key(c, bin_reading_stat, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_QUIT: if (keylen == 0 && extlen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); c->write_and_go = conn_closing; if (c->noreply) { conn_set_state(c, conn_closing); } } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: if (extlen == 0 && keylen == 0 && bodylen == 0) { bin_list_sasl_mechs(c); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_AUTH: case PROTOCOL_BINARY_CMD_SASL_STEP: if (extlen == 0 && keylen != 0) { bin_read_key(c, bin_reading_sasl_auth, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_TOUCH: case PROTOCOL_BINARY_CMD_GAT: case PROTOCOL_BINARY_CMD_GATQ: case PROTOCOL_BINARY_CMD_GATK: case PROTOCOL_BINARY_CMD_GATKQ: if (extlen == 4 && keylen != 0) { bin_read_key(c, bin_reading_touch_key, 4); } else { protocol_error = 1; } break; default: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, bodylen); } if (protocol_error) handle_binary_protocol_error(c); } static void process_bin_update(conn *c) { char *key; int nkey; int vlen; item *it; protocol_binary_request_set* req = binary_get_request(c); assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; /* fix byteorder in the request */ req->message.body.flags = ntohl(req->message.body.flags); req->message.body.expiration = ntohl(req->message.body.expiration); vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen); if (settings.verbose > 1) { int ii; if (c->cmd == PROTOCOL_BINARY_CMD_ADD) { fprintf(stderr, "<%d ADD ", c->sfd); } else if (c->cmd == PROTOCOL_BINARY_CMD_SET) { fprintf(stderr, "<%d SET ", c->sfd); } else { fprintf(stderr, "<%d REPLACE ", c->sfd); } for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, " Value len is %d", vlen); fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, req->message.body.flags, realtime(req->message.body.expiration), vlen+2); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* This error generating method eats the swallow value. Add here. */ c->sbytes = vlen; status = NO_MEMORY; } /* FIXME: losing c->cmd since it's translated below. refactor? */ LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, 0, key, nkey, req->message.body.expiration, ITEM_clsid(it), c->sfd); /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (c->cmd == PROTOCOL_BINARY_CMD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_ADD: c->cmd = NREAD_ADD; break; case PROTOCOL_BINARY_CMD_SET: c->cmd = NREAD_SET; break; case PROTOCOL_BINARY_CMD_REPLACE: c->cmd = NREAD_REPLACE; break; default: assert(0); } if (ITEM_get_cas(it) != 0) { c->cmd = NREAD_CAS; } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_append_prepend(conn *c) { char *key; int nkey; int vlen; item *it; assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; vlen = c->binary_header.request.bodylen - nkey; if (settings.verbose > 1) { fprintf(stderr, "Value len is %d\n", vlen); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, 0, 0, vlen+2); if (it == 0) { if (! item_size_ok(nkey, 0, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* OOM calls eat the swallow value. Add here. */ c->sbytes = vlen; } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_APPEND: c->cmd = NREAD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPEND: c->cmd = NREAD_PREPEND; break; default: assert(0); } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_flush(conn *c) { time_t exptime = 0; protocol_binary_request_flush* req = binary_get_request(c); rel_time_t new_oldest = 0; if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } if (c->binary_header.request.extlen == sizeof(req->message.body)) { exptime = ntohl(req->message.body.expiration); } if (exptime > 0) { new_oldest = realtime(exptime); } else { new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_response(c, NULL, 0, 0, 0); } static void process_bin_delete(conn *c) { item *it; uint32_t hv; protocol_binary_request_delete* req = binary_get_request(c); char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; assert(c != NULL); if (settings.verbose > 1) { int ii; fprintf(stderr, "Deleting "); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { uint64_t cas = ntohll(req->message.header.request.cas); if (cas == 0 || cas == ITEM_get_cas(it)) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); write_bin_response(c, NULL, 0, 0, 0); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); } do_item_remove(it); /* release our reference */ } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } item_unlock(hv); } static void complete_nread_binary(conn *c) { assert(c != NULL); assert(c->cmd >= 0); switch(c->substate) { case bin_reading_set_header: if (c->cmd == PROTOCOL_BINARY_CMD_APPEND || c->cmd == PROTOCOL_BINARY_CMD_PREPEND) { process_bin_append_prepend(c); } else { process_bin_update(c); } break; case bin_read_set_value: complete_update_bin(c); break; case bin_reading_get_key: case bin_reading_touch_key: process_bin_get_or_touch(c); break; case bin_reading_stat: process_bin_stat(c); break; case bin_reading_del_header: process_bin_delete(c); break; case bin_reading_incr_header: complete_incr_bin(c); break; case bin_read_flush_exptime: process_bin_flush(c); break; case bin_reading_sasl_auth: process_bin_sasl_auth(c); break; case bin_reading_sasl_auth_data: process_bin_complete_sasl_auth(c); break; default: fprintf(stderr, "Not handling substate %d\n", c->substate); assert(0); } } static void reset_cmd_handler(conn *c) { c->cmd = -1; c->substate = bin_no_state; if(c->item != NULL) { item_remove(c->item); c->item = NULL; } conn_shrink(c); if (c->rbytes > 0) { conn_set_state(c, conn_parse_cmd); } else { conn_set_state(c, conn_waiting); } } static void complete_nread(conn *c) { assert(c != NULL); assert(c->protocol == ascii_prot || c->protocol == binary_prot); if (c->protocol == ascii_prot) { complete_nread_ascii(c); } else if (c->protocol == binary_prot) { complete_nread_binary(c); } } /* Destination must always be chunked */ /* This should be part of item.c */ static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) { item_chunk *dch = (item_chunk *) ITEM_schunk(d_it); /* Advance dch until we find free space */ while (dch->size == dch->used) { if (dch->next) { dch = dch->next; } else { break; } } if (s_it->it_flags & ITEM_CHUNKED) { int remain = len; item_chunk *sch = (item_chunk *) ITEM_schunk(s_it); int copied = 0; /* Fills dch's to capacity, not straight copy sch in case data is * being added or removed (ie append/prepend) */ while (sch && dch && remain) { assert(dch->used <= dch->size); int todo = (dch->size - dch->used < sch->used - copied) ? dch->size - dch->used : sch->used - copied; if (remain < todo) todo = remain; memcpy(dch->data + dch->used, sch->data + copied, todo); dch->used += todo; copied += todo; remain -= todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, remain); if (tch) { dch = tch; } else { return -1; } } assert(copied <= sch->used); if (copied == sch->used) { copied = 0; sch = sch->next; } } /* assert that the destination had enough space for the source */ assert(remain == 0); } else { int done = 0; /* Fill dch's via a non-chunked item. */ while (len > done && dch) { int todo = (dch->size - dch->used < len - done) ? dch->size - dch->used : len - done; //assert(dch->size - dch->used != 0); memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo); done += todo; dch->used += todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, len - done); if (tch) { dch = tch; } else { return -1; } } } assert(len == done); } return 0; } static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) { if (comm == NREAD_APPEND) { if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes); memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes); } } else { /* NREAD_PREPEND */ if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes); memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes); } } return 0; } /* * Stores an item in the cache according to the semantics of one of the set * commands. In threaded mode, this is protected by the cache lock. * * Returns the state of storage. */ enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) { char *key = ITEM_key(it); item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE); enum store_item_type stored = NOT_STORED; item *new_it = NULL; uint32_t flags; if (old_it != NULL && comm == NREAD_ADD) { /* add only adds a nonexistent item, but promote to head of LRU */ do_item_update(old_it); } else if (!old_it && (comm == NREAD_REPLACE || comm == NREAD_APPEND || comm == NREAD_PREPEND)) { /* replace only replaces an existing value; don't store */ } else if (comm == NREAD_CAS) { /* validate cas operation */ if(old_it == NULL) { // LRU expired stored = NOT_FOUND; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.cas_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) { // cas validates // it and old_it may belong to different classes. // I'm updating the stats for the one that's getting pushed out pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); stored = STORED; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++; pthread_mutex_unlock(&c->thread->stats.mutex); if(settings.verbose > 1) { fprintf(stderr, "CAS: failure: expected %llu, got %llu\n", (unsigned long long)ITEM_get_cas(old_it), (unsigned long long)ITEM_get_cas(it)); } stored = EXISTS; } } else { int failed_alloc = 0; /* * Append - combine new and old record into single one. Here it's * atomic and thread-safe. */ if (comm == NREAD_APPEND || comm == NREAD_PREPEND) { /* * Validate CAS */ if (ITEM_get_cas(it) != 0) { // CAS much be equal if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) { stored = EXISTS; } } #ifdef EXTSTORE if ((old_it->it_flags & ITEM_HDR) != 0) { /* block append/prepend from working with extstore-d items. * also don't replace the header with the append chunk * accidentally, so mark as a failed_alloc. */ failed_alloc = 1; } else #endif if (stored == NOT_STORED) { /* we have it and old_it here - alloc memory to hold both */ /* flags was already lost - so recover them from ITEM_suffix(it) */ FLAGS_CONV(old_it, flags); new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */); /* copy data from it and old_it to new_it */ if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) { failed_alloc = 1; stored = NOT_STORED; // failed data copy, free up. if (new_it != NULL) item_remove(new_it); } else { it = new_it; } } } if (stored == NOT_STORED && failed_alloc == 0) { if (old_it != NULL) { STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); } else { do_item_link(it, hv); } c->cas = ITEM_get_cas(it); stored = STORED; } } if (old_it != NULL) do_item_remove(old_it); /* release our reference */ if (new_it != NULL) do_item_remove(new_it); if (stored == STORED) { c->cas = ITEM_get_cas(it); } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it), c->sfd); return stored; } typedef struct token_s { char *value; size_t length; } token_t; #define COMMAND_TOKEN 0 #define SUBCOMMAND_TOKEN 1 #define KEY_TOKEN 1 #define MAX_TOKENS 8 /* * Tokenize the command string by replacing whitespace with '\0' and update * the token array tokens with pointer to start of each token and length. * Returns total number of tokens. The last valid token is the terminal * token (value points to the first unprocessed character of the string and * length zero). * * Usage example: * * while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) { * for(int ix = 0; tokens[ix].length != 0; ix++) { * ... * } * ncommand = tokens[ix].value - command; * command = tokens[ix].value; * } */ static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) { char *s, *e; size_t ntokens = 0; size_t len = strlen(command); unsigned int i = 0; assert(command != NULL && tokens != NULL && max_tokens > 1); s = e = command; for (i = 0; i < len; i++) { if (*e == ' ') { if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; *e = '\0'; if (ntokens == max_tokens - 1) { e++; s = e; /* so we don't add an extra token */ break; } } s = e + 1; } e++; } if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; } /* * If we scanned the whole string, the terminal value pointer is null, * otherwise it is the first unprocessed character. */ tokens[ntokens].value = *e == '\0' ? NULL : e; tokens[ntokens].length = 0; ntokens++; return ntokens; } /* set up a connection to write a buffer then free it, used for stats */ static void write_and_free(conn *c, char *buf, int bytes) { if (buf) { c->write_and_free = buf; c->wcurr = buf; c->wbytes = bytes; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; } else { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } } static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens) { int noreply_index = ntokens - 2; /* NOTE: this function is not the first place where we are going to send the reply. We could send it instead from process_command() if the request line has wrong number of tokens. However parsing malformed line for "noreply" option is not reliable anyway, so it can't be helped. */ if (tokens[noreply_index].value && strcmp(tokens[noreply_index].value, "noreply") == 0) { c->noreply = true; } return c->noreply; } void append_stat(const char *name, ADD_STAT add_stats, conn *c, const char *fmt, ...) { char val_str[STAT_VAL_LEN]; int vlen; va_list ap; assert(name); assert(add_stats); assert(c); assert(fmt); va_start(ap, fmt); vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap); va_end(ap); add_stats(name, strlen(name), val_str, vlen, c); } inline static void process_stats_detail(conn *c, const char *command) { assert(c != NULL); if (strcmp(command, "on") == 0) { settings.detail_enabled = 1; out_string(c, "OK"); } else if (strcmp(command, "off") == 0) { settings.detail_enabled = 0; out_string(c, "OK"); } else if (strcmp(command, "dump") == 0) { int len; char *stats = stats_prefix_dump(&len); write_and_free(c, stats, len); } else { out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump"); } } /* return server specific stats only */ static void server_stats(ADD_STAT add_stats, conn *c) { pid_t pid = getpid(); rel_time_t now = current_time; struct thread_stats thread_stats; threadlocal_stats_aggregate(&thread_stats); struct slab_stats slab_stats; slab_stats_aggregate(&thread_stats, &slab_stats); #ifdef EXTSTORE struct extstore_stats st; #endif #ifndef WIN32 struct rusage usage; getrusage(RUSAGE_SELF, &usage); #endif /* !WIN32 */ STATS_LOCK(); APPEND_STAT("pid", "%lu", (long)pid); APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL); APPEND_STAT("time", "%ld", now + (long)process_started); APPEND_STAT("version", "%s", VERSION); APPEND_STAT("libevent", "%s", event_get_version()); APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *))); #ifndef WIN32 append_stat("rusage_user", add_stats, c, "%ld.%06ld", (long)usage.ru_utime.tv_sec, (long)usage.ru_utime.tv_usec); append_stat("rusage_system", add_stats, c, "%ld.%06ld", (long)usage.ru_stime.tv_sec, (long)usage.ru_stime.tv_usec); #endif /* !WIN32 */ APPEND_STAT("max_connections", "%d", settings.maxconns); APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1); APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns); if (settings.maxconns_fast) { APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns); } APPEND_STAT("connection_structures", "%u", stats_state.conn_structs); APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds); APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds); APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds); APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds); APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds); APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits); APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses); APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired); APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed); #ifdef EXTSTORE if (c->thread->storage) { APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore); APPEND_STAT("get_aborted_extstore", "%llu", (unsigned long long)thread_stats.get_aborted_extstore); APPEND_STAT("get_oom_extstore", "%llu", (unsigned long long)thread_stats.get_oom_extstore); APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore); APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore); APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore); } #endif APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses); APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits); APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses); APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits); APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses); APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits); APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses); APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits); APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval); APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits); APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses); APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds); APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors); if (settings.idle_timeout) { APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks); } APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read); APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written); APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns); APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num); APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us); APPEND_STAT("threads", "%d", settings.num_threads); APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields); APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level); APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes); APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding); if (settings.slab_reassign) { APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues); APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues); APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem); APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim); APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items); APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes); APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running); APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved); } if (settings.lru_crawler) { APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running); APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts); } if (settings.lru_maintainer_thread) { APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles); } APPEND_STAT("malloc_fails", "%llu", (unsigned long long)stats.malloc_fails); APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped); APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written); APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped); APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent); STATS_UNLOCK(); #ifdef EXTSTORE if (c->thread->storage) { STATS_LOCK(); APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost); APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues); APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped); STATS_UNLOCK(); extstore_get_stats(c->thread->storage, &st); APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs); APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions); APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims); APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free); APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used); APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted); APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read); APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written); APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used); APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted); APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written); APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read); APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used); APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented); APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size)); APPEND_STAT("extstore_io_queue", "%llu", (unsigned long long)(st.io_queue)); } #endif #ifdef TLS if (settings.ssl_enabled) { SSL_LOCK(); APPEND_STAT("time_since_server_cert_refresh", "%u", now - settings.ssl_last_cert_refresh_time); SSL_UNLOCK(); } #endif } static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("auth_enabled_ascii", "%s", settings.auth_file ? settings.auth_file : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio); APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", "no"); // setting is dead, cannot be yes. #ifdef HAVE_DROP_PRIVILEGES APPEND_STAT("drop_privileges", "%s", settings.drop_privileges ? "yes" : "no"); #endif #ifdef EXTSTORE APPEND_STAT("ext_item_size", "%u", settings.ext_item_size); APPEND_STAT("ext_item_age", "%u", settings.ext_item_age); APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl); APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate); APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size); APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under); APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under); APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag); APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio); APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no"); #endif #ifdef TLS APPEND_STAT("ssl_enabled", "%s", settings.ssl_enabled ? "yes" : "no"); APPEND_STAT("ssl_chain_cert", "%s", settings.ssl_chain_cert); APPEND_STAT("ssl_key", "%s", settings.ssl_key); APPEND_STAT("ssl_verify_mode", "%d", settings.ssl_verify_mode); APPEND_STAT("ssl_keyformat", "%d", settings.ssl_keyformat); APPEND_STAT("ssl_ciphers", "%s", settings.ssl_ciphers ? settings.ssl_ciphers : "NULL"); APPEND_STAT("ssl_ca_cert", "%s", settings.ssl_ca_cert ? settings.ssl_ca_cert : "NULL"); APPEND_STAT("ssl_wbuf_size", "%u", settings.ssl_wbuf_size); #endif } static int nz_strcmp(int nzlength, const char *nz, const char *z) { int zlength=strlen(z); return (zlength == nzlength) && (strncmp(nz, z, zlength) == 0) ? 0 : -1; } static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c) { bool ret = true; if (add_stats != NULL) { if (!stat_type) { /* prepare general statistics for the engine */ STATS_LOCK(); APPEND_STAT("bytes", "%llu", (unsigned long long)stats_state.curr_bytes); APPEND_STAT("curr_items", "%llu", (unsigned long long)stats_state.curr_items); APPEND_STAT("total_items", "%llu", (unsigned long long)stats.total_items); STATS_UNLOCK(); APPEND_STAT("slab_global_page_pool", "%u", global_page_pool_size(NULL)); item_stats_totals(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "items") == 0) { item_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "slabs") == 0) { slabs_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes") == 0) { item_stats_sizes(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_enable") == 0) { item_stats_sizes_enable(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_disable") == 0) { item_stats_sizes_disable(add_stats, c); } else { ret = false; } } else { ret = false; } return ret; } static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; size_t pathlen = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: // this strncpy call originally could piss off an address // sanitizer; we supplied the size of the dest buf as a limiter, // but optimized versions of strncpy could read past the end of // *src while looking for a null terminator. Since buf and // sun_path here are both on the stack they could even overlap, // which is "undefined". In all OSS versions of strncpy I could // find this has no effect; it'll still only copy until the first null // terminator is found. Thus it's possible to get the OS to // examine past the end of sun_path but it's unclear to me if this // can cause any actual problem. // // We need a safe_strncpy util function but I'll punt on figuring // that out for now. pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path); if (MAXPATHLEN <= pathlen) { pathlen = MAXPATHLEN - 1; } strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, pathlen); addr_text[pathlen] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } } static void conn_to_str(const conn *c, char *addr, char *svr_addr) { if (!c) { strcpy(addr, "<null>"); } else if (c->state == conn_closed) { strcpy(addr, "<closed>"); } else { struct sockaddr_in6 local_addr; struct sockaddr *sock_addr = (void *)&c->request_addr; /* For listen ports and idle UDP ports, show listen address */ if (c->state == conn_listening || (IS_UDP(c->transport) && c->state == conn_read)) { socklen_t local_addr_len = sizeof(local_addr); if (getsockname(c->sfd, (struct sockaddr *)&local_addr, &local_addr_len) == 0) { sock_addr = (struct sockaddr *)&local_addr; } } get_conn_text(c, sock_addr->sa_family, addr, sock_addr); if (c->state != conn_listening && !(IS_UDP(c->transport) && c->state == conn_read)) { struct sockaddr_storage svr_sock_addr; socklen_t svr_addr_len = sizeof(svr_sock_addr); getsockname(c->sfd, (struct sockaddr *)&svr_sock_addr, &svr_addr_len); get_conn_text(c, svr_sock_addr.ss_family, svr_addr, (struct sockaddr *)&svr_sock_addr); } } } static void process_stats_conns(ADD_STAT add_stats, void *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; size_t extras_len = sizeof("unix:") + sizeof("65535"); char addr[MAXPATHLEN + extras_len]; char svr_addr[MAXPATHLEN + extras_len]; int klen = 0, vlen = 0; assert(add_stats); for (i = 0; i < max_fds; i++) { if (conns[i]) { /* This is safe to do unlocked because conns are never freed; the * worst that'll happen will be a minor inconsistency in the * output -- not worth the complexity of the locking that'd be * required to prevent it. */ if (IS_UDP(conns[i]->transport)) { APPEND_NUM_STAT(i, "UDP", "%s", "UDP"); } if (conns[i]->state != conn_closed) { conn_to_str(conns[i], addr, svr_addr); APPEND_NUM_STAT(i, "addr", "%s", addr); if (conns[i]->state != conn_listening && !(IS_UDP(conns[i]->transport) && conns[i]->state == conn_read)) { APPEND_NUM_STAT(i, "listen_addr", "%s", svr_addr); } APPEND_NUM_STAT(i, "state", "%s", state_text(conns[i]->state)); APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d", current_time - conns[i]->last_cmd_time); } } } } #ifdef EXTSTORE static void process_extstore_stats(ADD_STAT add_stats, conn *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; int klen = 0, vlen = 0; struct extstore_stats st; assert(add_stats); void *storage = c->thread->storage; extstore_get_stats(storage, &st); st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data)); extstore_get_page_data(storage, &st); for (i = 0; i < st.page_count; i++) { APPEND_NUM_STAT(i, "version", "%llu", (unsigned long long) st.page_data[i].version); APPEND_NUM_STAT(i, "bytes", "%llu", (unsigned long long) st.page_data[i].bytes_used); APPEND_NUM_STAT(i, "bucket", "%u", st.page_data[i].bucket); APPEND_NUM_STAT(i, "free_bucket", "%u", st.page_data[i].free_bucket); } } #endif static void process_stat(conn *c, token_t *tokens, const size_t ntokens) { const char *subcommand = tokens[SUBCOMMAND_TOKEN].value; assert(c != NULL); if (ntokens < 2) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (ntokens == 2) { server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strcmp(subcommand, "reset") == 0) { stats_reset(); out_string(c, "RESET"); return ; } else if (strcmp(subcommand, "detail") == 0) { /* NOTE: how to tackle detail with binary? */ if (ntokens < 4) process_stats_detail(c, ""); /* outputs the error message */ else process_stats_detail(c, tokens[2].value); /* Output already generated */ return ; } else if (strcmp(subcommand, "settings") == 0) { process_stat_settings(&append_stats, c); } else if (strcmp(subcommand, "cachedump") == 0) { char *buf; unsigned int bytes, id, limit = 0; if (!settings.dump_enabled) { out_string(c, "CLIENT_ERROR stats cachedump not allowed"); return; } if (ntokens < 5) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (!safe_strtoul(tokens[2].value, &id) || !safe_strtoul(tokens[3].value, &limit)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (id >= MAX_NUMBER_OF_SLAB_CLASSES) { out_string(c, "CLIENT_ERROR Illegal slab id"); return; } buf = item_cachedump(id, limit, &bytes); write_and_free(c, buf, bytes); return ; } else if (strcmp(subcommand, "conns") == 0) { process_stats_conns(&append_stats, c); #ifdef EXTSTORE } else if (strcmp(subcommand, "extstore") == 0) { process_extstore_stats(&append_stats, c); #endif } else { /* getting here means that the subcommand is either engine specific or is invalid. query the engine and see. */ if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { out_string(c, "ERROR"); } return ; } /* append terminator and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } /* client flags == 0 means use no storage for client flags */ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) { char *p = suffix; *p = ' '; p++; if (FLAGS_SIZE(it) == 0) { *p = '0'; p++; } else { p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p); } *p = ' '; p = itoa_u32(nbytes-2, p+1); if (return_cas) { *p = ' '; p = itoa_u64(ITEM_get_cas(it), p+1); } *p = '\r'; *(p+1) = '\n'; *(p+2) = '\0'; return (p - suffix) + 2; } #define IT_REFCOUNT_LIMIT 60000 static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) { item *it; if (should_touch) { it = item_touch(key, nkey, exptime, c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it && it->refcount > IT_REFCOUNT_LIMIT) { item_remove(it); it = NULL; } return it; } static inline int _ascii_get_expand_ilist(conn *c, int i) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } } return 0; } static inline char *_ascii_get_suffix_buf(conn *c, int i) { char *suffix; /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return NULL; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); return NULL; } *(c->suffixlist + i) = suffix; return suffix; } #ifdef EXTSTORE // FIXME: This runs in the IO thread. to get better IO performance this should // simply mark the io wrapper with the return value and decrement wrapleft, if // zero redispatching. Still a bit of work being done in the side thread but // minimized at least. static void _get_extstore_cb(void *e, obj_io *io, int ret) { // FIXME: assumes success io_wrap *wrap = (io_wrap *)io->data; conn *c = wrap->c; assert(wrap->active == true); item *read_it = (item *)io->buf; bool miss = false; // TODO: How to do counters for hit/misses? if (ret < 1) { miss = true; } else { uint32_t crc2; uint32_t crc = (uint32_t) read_it->exptime; int x; // item is chunked, crc the iov's if (io->iov != NULL) { // first iov is the header, which we don't use beyond crc crc2 = crc32c(0, (char *)io->iov[0].iov_base+STORE_OFFSET, io->iov[0].iov_len-STORE_OFFSET); // make sure it's not sent. hack :( io->iov[0].iov_len = 0; for (x = 1; x < io->iovcnt; x++) { crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len); } } else { crc2 = crc32c(0, (char *)read_it+STORE_OFFSET, io->len-STORE_OFFSET); } if (crc != crc2) { miss = true; wrap->badcrc = true; } } if (miss) { int i; struct iovec *v; // TODO: This should be movable to the worker thread. if (c->protocol == binary_prot) { protocol_binary_response_header *header = (protocol_binary_response_header *)c->wbuf; // this zeroes out the iovecs since binprot never stacks them. if (header->response.keylen) { write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey); } else { write_bin_miss_response(c, 0, 0); } } else { for (i = 0; i < wrap->iovec_count; i++) { v = &c->iov[wrap->iovec_start + i]; v->iov_len = 0; v->iov_base = NULL; } } wrap->miss = true; } else { assert(read_it->slabs_clsid != 0); // kill \r\n for binprot if (io->iov == NULL) { c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it); if (c->protocol == binary_prot) c->iov[wrap->iovec_data].iov_len -= 2; } else { // FIXME: Might need to go back and ensure chunked binprots don't // ever span two chunks for the final \r\n if (c->protocol == binary_prot) { if (io->iov[io->iovcnt-1].iov_len >= 2) { io->iov[io->iovcnt-1].iov_len -= 2; } else { io->iov[io->iovcnt-1].iov_len = 0; io->iov[io->iovcnt-2].iov_len -= 1; } } } wrap->miss = false; // iov_len is already set // TODO: Should do that here instead and cuddle in the wrap object } c->io_wrapleft--; wrap->active = false; //assert(c->io_wrapleft >= 0); // All IO's have returned, lets re-attach this connection to our original // thread. if (c->io_wrapleft == 0) { assert(c->io_queued == true); c->io_queued = false; redispatch_conn(c); } } // FIXME: This completely breaks UDP support. static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) { #ifdef NEED_ALIGN item_hdr hdr; memcpy(&hdr, ITEM_data(it), sizeof(hdr)); #else item_hdr *hdr = (item_hdr *)ITEM_data(it); #endif size_t ntotal = ITEM_ntotal(it); unsigned int clsid = slabs_clsid(ntotal); item *new_it; bool chunked = false; if (ntotal > settings.slab_chunk_size_max) { // Pull a chunked item header. uint32_t flags; FLAGS_CONV(it, flags); new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes); assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED)); chunked = true; } else { new_it = do_item_alloc_pull(ntotal, clsid); } if (new_it == NULL) return -1; assert(!c->io_queued); // FIXME: debugging. // so we can free the chunk on a miss new_it->slabs_clsid = clsid; io_wrap *io = do_cache_alloc(c->thread->io_cache); io->active = true; io->miss = false; io->badcrc = false; // io_wrap owns the reference for this object now. io->hdr_it = it; // FIXME: error handling. // The offsets we'll wipe on a miss. io->iovec_start = iovst; io->iovec_count = iovcnt; // This is probably super dangerous. keep it at 0 and fill into wrap // object? if (chunked) { unsigned int ciovcnt = 1; size_t remain = new_it->nbytes; item_chunk *chunk = (item_chunk *) ITEM_schunk(new_it); io->io.iov = &c->iov[c->iovused]; // fill the header so we can get the full data + crc back. add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes); while (remain > 0) { chunk = do_item_alloc_chunk(chunk, remain); if (chunk == NULL) { item_remove(new_it); do_cache_free(c->thread->io_cache, io); return -1; } add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size); chunk->used = (remain < chunk->size) ? remain : chunk->size; remain -= chunk->size; ciovcnt++; } io->io.iovcnt = ciovcnt; // header object was already accounted for, remove one from total io->iovec_count += ciovcnt-1; } else { io->io.iov = NULL; io->iovec_data = c->iovused; add_iov(c, "", it->nbytes); } io->io.buf = (void *)new_it; // The offset we'll fill in on a hit. io->c = c; // We need to stack the sub-struct IO's together as well. if (c->io_wraplist) { io->io.next = &c->io_wraplist->io; } else { io->io.next = NULL; } // IO queue for this connection. io->next = c->io_wraplist; c->io_wraplist = io; assert(c->io_wrapleft >= 0); c->io_wrapleft++; // reference ourselves for the callback. io->io.data = (void *)io; // Now, fill in io->io based on what was in our header. #ifdef NEED_ALIGN io->io.page_version = hdr.page_version; io->io.page_id = hdr.page_id; io->io.offset = hdr.offset; #else io->io.page_version = hdr->page_version; io->io.page_id = hdr->page_id; io->io.offset = hdr->offset; #endif io->io.len = ntotal; io->io.mode = OBJ_IO_READ; io->io.cb = _get_extstore_cb; //fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data); // FIXME: This stat needs to move to reflect # of flash hits vs misses // for now it's a good gauge on how often we request out to flash at // least. pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); return 0; } #endif /* ntokens is overwritten here... shrug.. */ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) { char *key; size_t nkey; int i = 0; int si = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; int32_t exptime_int = 0; rel_time_t exptime = 0; bool fail_length = false; assert(c != NULL); if (should_touch) { // For get and touch commands, use first token as exptime if (!safe_strtol(tokens[1].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } key_token++; exptime = realtime(exptime_int); } do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if (nkey > KEY_MAX_LENGTH) { fail_length = true; goto stop; } it = limited_get(key, nkey, c, exptime, should_touch); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (_ascii_get_expand_ilist(c, i) != 0) { item_remove(it); goto stop; } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); int nbytes; suffix = _ascii_get_suffix_buf(c, si); if (suffix == NULL) { item_remove(it); goto stop; } si++; nbytes = it->nbytes; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); goto stop; } #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { if (_get_extstore(c, it, c->iovused-3, 4) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); item_remove(it); goto stop; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { #else if ((it->it_flags & ITEM_CHUNKED) == 0) { #endif add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); goto stop; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.lru_hits[it->slabs_clsid]++; c->thread->stats.get_cmds++; } pthread_mutex_unlock(&c->thread->stats.mutex); #ifdef EXTSTORE /* If ITEM_HDR, an io_wrap owns the reference. */ if ((it->it_flags & ITEM_HDR) == 0) { *(c->ilist + i) = it; i++; } #else *(c->ilist + i) = it; i++; #endif } else { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_misses++; c->thread->stats.get_cmds++; } MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); pthread_mutex_unlock(&c->thread->stats.mutex); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); stop: c->icurr = c->ilist; c->ileft = i; c->suffixcurr = c->suffixlist; c->suffixleft = si; if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { if (fail_length) { out_string(c, "CLIENT_ERROR bad command line format"); } else { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } conn_release_items(c); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { char *key; size_t nkey; unsigned int flags; int32_t exptime_int = 0; time_t exptime; int vlen; uint64_t req_cas_id=0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags) && safe_strtol(tokens[3].value, &exptime_int) && safe_strtol(tokens[4].value, (int32_t *)&vlen))) { out_string(c, "CLIENT_ERROR bad command line format"); return; } /* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */ exptime = exptime_int; /* Negative exptimes can underflow and end up immortal. realtime() will immediately expire values that are greater than REALTIME_MAXDELTA, but less than process_started, so lets aim for that. */ if (exptime < 0) exptime = REALTIME_MAXDELTA + 1; // does cas value exist? if (handle_cas) { if (!safe_strtoull(tokens[5].value, &req_cas_id)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } if (vlen < 0 || vlen > (INT_MAX - 2)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } vlen += 2; if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, flags, realtime(exptime), vlen); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, flags, vlen)) { out_string(c, "SERVER_ERROR object too large for cache"); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR out of memory storing object"); status = NO_MEMORY; } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, comm, key, nkey, 0, 0, c->sfd); /* swallow the data line */ c->write_and_go = conn_swallow; c->sbytes = vlen; /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (comm == NREAD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } return; } ITEM_set_cas(it, req_cas_id); c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = it->nbytes; c->cmd = comm; conn_set_state(c, conn_nread); } static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; int32_t exptime_int = 0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtol(tokens[2].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } it = item_touch(key, nkey, realtime(exptime_int), c); if (it) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "TOUCHED"); item_remove(it); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) { char temp[INCR_MAX_STORAGE_LEN]; uint64_t delta; char *key; size_t nkey; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtoull(tokens[2].value, &delta)) { out_string(c, "CLIENT_ERROR invalid numeric delta argument"); return; } switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) { case OK: out_string(c, temp); break; case NON_NUMERIC: out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value"); break; case EOM: out_of_memory(c, "SERVER_ERROR out of memory"); break; case DELTA_ITEM_NOT_FOUND: pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); break; case DELTA_ITEM_CAS_MISMATCH: break; /* Should never get here */ } } /* * adds a delta value to a numeric item. * * c connection requesting the operation * it item to adjust * incr true to increment value, false to decrement * delta amount to adjust value by * buf buffer for response string * * returns a response string to send back to the client. */ enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, const bool incr, const int64_t delta, char *buf, uint64_t *cas, const uint32_t hv) { char *ptr; uint64_t value; int res; item *it; it = do_item_get(key, nkey, hv, c, DONT_UPDATE); if (!it) { return DELTA_ITEM_NOT_FOUND; } /* Can't delta zero byte values. 2-byte are the "\r\n" */ /* Also can't delta for chunked items. Too large to be a number */ #ifdef EXTSTORE if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) { #else if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) { #endif do_item_remove(it); return NON_NUMERIC; } if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { do_item_remove(it); return DELTA_ITEM_CAS_MISMATCH; } ptr = ITEM_data(it); if (!safe_strtoull(ptr, &value)) { do_item_remove(it); return NON_NUMERIC; } if (incr) { value += delta; MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); } else { if(delta > value) { value = 0; } else { value -= delta; } MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); } pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; } else { c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); itoa_u64(value, buf); res = strlen(buf); /* refcount == 2 means we are the only ones holding the item, and it is * linked. We hold the item's lock in this function, so refcount cannot * increase. */ if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ /* When changing the value without replacing the item, we need to update the CAS on the existing item. */ /* We also need to fiddle it in the sizes tracker in case the tracking * was enabled at runtime, since it relies on the CAS value to know * whether to remove an item or not. */ item_stats_sizes_remove(it); ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); item_stats_sizes_add(it); memcpy(ITEM_data(it), buf, res); memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); do_item_update(it); } else if (it->refcount > 1) { item *new_it; uint32_t flags; FLAGS_CONV(it, flags); new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); if (new_it == 0) { do_item_remove(it); return EOM; } memcpy(ITEM_data(new_it), buf, res); memcpy(ITEM_data(new_it) + res, "\r\n", 2); item_replace(it, new_it, hv); // Overwrite the older item's CAS with our new CAS since we're // returning the CAS of the old item below. ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); do_item_remove(new_it); /* release our reference */ } else { /* Should never get here. This means we somehow fetched an unlinked * item. TODO: Add a counter? */ if (settings.verbose) { fprintf(stderr, "Tried to do incr/decr on invalid item\n"); } if (it->refcount == 1) do_item_remove(it); return DELTA_ITEM_NOT_FOUND; } if (cas) { *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ } do_item_remove(it); /* release our reference */ return OK; } static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; item *it; uint32_t hv; assert(c != NULL); if (ntokens > 3) { bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0; bool sets_noreply = set_noreply_maybe(c, tokens, ntokens); bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply)) || (ntokens == 5 && hold_is_zero && sets_noreply); if (!valid) { out_string(c, "CLIENT_ERROR bad command line format. " "Usage: delete <key> [noreply]"); return; } } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); do_item_remove(it); /* release our reference */ out_string(c, "DELETED"); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } item_unlock(hv); } static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[1].value, NULL, 10); settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level; out_string(c, "OK"); return; } #ifdef MEMCACHED_DEBUG static void process_misbehave_command(conn *c) { int allowed = 0; // try opening new TCP socket int i = socket(AF_INET, SOCK_STREAM, 0); if (i != -1) { allowed++; close(i); } // try executing new commands i = system("sleep 0"); if (i != -1) { allowed++; } if (allowed) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; double ratio; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[2].value, "ratio") == 0) { if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) { out_string(c, "ERROR"); return; } settings.slab_automove_ratio = ratio; } else { level = strtoul(tokens[2].value, NULL, 10); if (level == 0) { settings.slab_automove = 0; } else if (level == 1 || level == 2) { settings.slab_automove = level; } else { out_string(c, "ERROR"); return; } } out_string(c, "OK"); return; } /* TODO: decide on syntax for sampling? */ static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) { uint16_t f = 0; int x; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (ntokens > 2) { for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) { if ((strcmp(tokens[x].value, "rawcmds") == 0)) { f |= LOG_RAWCMDS; } else if ((strcmp(tokens[x].value, "evictions") == 0)) { f |= LOG_EVICTIONS; } else if ((strcmp(tokens[x].value, "fetchers") == 0)) { f |= LOG_FETCHERS; } else if ((strcmp(tokens[x].value, "mutations") == 0)) { f |= LOG_MUTATIONS; } else if ((strcmp(tokens[x].value, "sysevents") == 0)) { f |= LOG_SYSEVENTS; } else { out_string(c, "ERROR"); return; } } } else { f |= LOG_FETCHERS; } switch(logger_add_watcher(c, c->sfd, f)) { case LOGGER_ADD_WATCHER_TOO_MANY: out_string(c, "WATCHER_TOO_MANY log watcher limit reached"); break; case LOGGER_ADD_WATCHER_FAILED: out_string(c, "WATCHER_FAILED failed to add log watcher"); break; case LOGGER_ADD_WATCHER_OK: conn_set_state(c, conn_watch); event_del(&c->event); break; } } static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t memlimit; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (!safe_strtoul(tokens[1].value, &memlimit)) { out_string(c, "ERROR"); } else { if (memlimit < 8) { out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m"); } else { if (memlimit > 1000000000) { out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes"); } else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) { if (settings.verbose > 0) { fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit); } out_string(c, "OK"); } else { out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust"); } } } } static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; double hot_factor; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtod(tokens[4].value, &hot_factor) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0 || hot_factor <= 0) { out_string(c, "ERROR hot/warm age factors must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_factor = hot_factor; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } #ifdef EXTSTORE static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) { set_noreply_maybe(c, tokens, ntokens); bool ok = true; if (ntokens < 4) { ok = false; } else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) { /* per-slab-class free chunk setting. */ unsigned int clsid = 0; unsigned int limit = 0; if (!safe_strtoul(tokens[2].value, &clsid) || !safe_strtoul(tokens[3].value, &limit)) { ok = false; } else { if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) { settings.ext_free_memchunks[clsid] = limit; } else { ok = false; } } } else if (strcmp(tokens[1].value, "item_size") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_size)) ok = false; } else if (strcmp(tokens[1].value, "item_age") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_age)) ok = false; } else if (strcmp(tokens[1].value, "low_ttl") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl)) ok = false; } else if (strcmp(tokens[1].value, "recache_rate") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate)) ok = false; } else if (strcmp(tokens[1].value, "compact_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under)) ok = false; } else if (strcmp(tokens[1].value, "drop_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under)) ok = false; } else if (strcmp(tokens[1].value, "max_frag") == 0) { if (!safe_strtod(tokens[2].value, &settings.ext_max_frag)) ok = false; } else if (strcmp(tokens[1].value, "drop_unread") == 0) { unsigned int v; if (!safe_strtoul(tokens[2].value, &v)) { ok = false; } else { settings.ext_drop_unread = v == 0 ? false : true; } } else { ok = false; } if (!ok) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_command(conn *c, char *command) { token_t tokens[MAX_TOKENS]; size_t ntokens; int comm; assert(c != NULL); MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); if (settings.verbose > 1) fprintf(stderr, "<%d %s\n", c->sfd, command); /* * for commands set/add/replace, we build an item and read the data * directly into it, then continue in nread_complete(). */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR out of memory preparing response"); return; } ntokens = tokenize_command(command, tokens, MAX_TOKENS); if (ntokens >= 3 && ((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) || (strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) { process_get_command(c, tokens, ntokens, false, false); } else if ((ntokens == 6 || ntokens == 7) && ((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) || (strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) || (strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) || (strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) || (strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) { process_update_command(c, tokens, ntokens, comm, false); } else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) { process_update_command(c, tokens, ntokens, comm, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 1); } else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) { process_get_command(c, tokens, ntokens, true, false); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 0); } else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) { process_delete_command(c, tokens, ntokens); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) { process_touch_command(c, tokens, ntokens); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) { process_get_command(c, tokens, ntokens, false, true); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) { process_get_command(c, tokens, ntokens, true, true); } else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) { process_stat(c, tokens, ntokens); } else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) { time_t exptime = 0; rel_time_t new_oldest = 0; set_noreply_maybe(c, tokens, ntokens); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats out_string(c, "CLIENT_ERROR flush_all not allowed"); return; } if (ntokens != (c->noreply ? 3 : 2)) { exptime = strtol(tokens[1].value, NULL, 10); if(errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } /* If exptime is zero realtime() would return zero too, and realtime(exptime) - 1 would overflow to the max unsigned value. So we process exptime == 0 the same way we do when no delay is given at all. */ if (exptime > 0) { new_oldest = realtime(exptime); } else { /* exptime == 0 */ new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } out_string(c, "OK"); return; } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) { out_string(c, "VERSION " VERSION); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) { conn_set_state(c, conn_closing); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) { if (settings.shutdown_command) { conn_set_state(c, conn_closing); raise(SIGINT); } else { out_string(c, "ERROR: shutdown not enabled"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) { if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) { int src, dst, rv; if (settings.slab_reassign == false) { out_string(c, "CLIENT_ERROR slab reassignment disabled"); return; } src = strtol(tokens[2].value, NULL, 10); dst = strtol(tokens[3].value, NULL, 10); if (errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } rv = slabs_reassign(src, dst); switch (rv) { case REASSIGN_OK: out_string(c, "OK"); break; case REASSIGN_RUNNING: out_string(c, "BUSY currently processing reassign request"); break; case REASSIGN_BADCLASS: out_string(c, "BADCLASS invalid src or dst class id"); break; case REASSIGN_NOSPARE: out_string(c, "NOSPARE source class has no spare pages"); break; case REASSIGN_SRC_DST_SAME: out_string(c, "SAME src and dst class are identical"); break; } return; } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) { process_slabs_automove_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) { if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) { int rv; if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0, settings.lru_crawler_tocrawl); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) { if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } if (!settings.dump_enabled) { out_string(c, "ERROR metadump not allowed"); return; } int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP, c, c->sfd, LRU_CRAWLER_CAP_REMAINING); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); // TODO: Don't reuse conn_watch here. conn_set_state(c, conn_watch); event_del(&c->event); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) { uint32_t tocrawl; if (!safe_strtoul(tokens[2].value, &tocrawl)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } settings.lru_crawler_tocrawl = tocrawl; out_string(c, "OK"); return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) { uint32_t tosleep; if (!safe_strtoul(tokens[2].value, &tosleep)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (tosleep > 1000000) { out_string(c, "CLIENT_ERROR sleep must be one second or less"); return; } settings.lru_crawler_sleep = tosleep; out_string(c, "OK"); return; } else if (ntokens == 3) { if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) { if (start_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to start lru crawler thread"); } } else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) { if (stop_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to stop lru crawler thread"); } } else { out_string(c, "ERROR"); } return; } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) { process_watch_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) { process_memlimit_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) { process_verbosity_command(c, tokens, ntokens); } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) { process_lru_command(c, tokens, ntokens); #ifdef MEMCACHED_DEBUG // commands which exist only for testing the memcached's security protection } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) { process_misbehave_command(c); #endif #ifdef EXTSTORE } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) { process_extstore_command(c, tokens, ntokens); #endif #ifdef TLS } else if (ntokens == 2 && strcmp(tokens[COMMAND_TOKEN].value, "refresh_certs") == 0) { set_noreply_maybe(c, tokens, ntokens); char *errmsg = NULL; if (refresh_certs(&errmsg)) { out_string(c, "OK"); } else { write_and_free(c, errmsg, strlen(errmsg)); } return; #endif } else { if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) { conn_set_state(c, conn_closing); } else { out_string(c, "ERROR"); } } return; } static int try_read_command_negotiate(conn *c) { assert(c->protocol == negotiating_prot); assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; c->try_read_command = try_read_command_binary; } else { // authentication doesn't work with negotiated protocol. c->protocol = ascii_prot; c->try_read_command = try_read_command_ascii; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } return c->try_read_command(c); } static int try_read_command_udp(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; return try_read_command_binary(c); } else { c->protocol = ascii_prot; return try_read_command_ascii(c); } } static int try_read_command_binary(conn *c) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR Out of memory allocating headers"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; c->last_cmd_time = current_time; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } return 1; } static int try_read_command_asciiauth(conn *c) { token_t tokens[MAX_TOKENS]; size_t ntokens; char *cont = NULL; // TODO: move to another function. if (!c->sasl_started) { char *el; uint32_t size = 0; // impossible for the auth command to be this short. if (c->rbytes < 2) return 0; el = memchr(c->rcurr, '\n', c->rbytes); // If no newline after 1k, getting junk data, close out. if (!el) { if (c->rbytes > 1024) { conn_set_state(c, conn_closing); return 1; } return 0; } // Looking for: "set foo 0 0 N\r\nuser pass\r\n" // key, flags, and ttl are ignored. N is used to see if we have the rest. // so tokenize doesn't walk past into the value. // it's fine to leave the \r in, as strtoul will stop at it. *el = '\0'; ntokens = tokenize_command(c->rcurr, tokens, MAX_TOKENS); // ensure the buffer is consumed. c->rbytes -= (el - c->rcurr) + 1; c->rcurr += (el - c->rcurr) + 1; // final token is a NULL ender, so we have one more than expected. if (ntokens < 6 || strcmp(tokens[0].value, "set") != 0 || !safe_strtoul(tokens[4].value, &size)) { out_string(c, "CLIENT_ERROR unauthenticated"); return 1; } // we don't actually care about the key at all; it can be anything. // we do care about the size of the remaining read. c->rlbytes = size + 2; c->sasl_started = true; // reuse from binprot sasl, but not sasl :) } if (c->rbytes < c->rlbytes) { // need more bytes. return 0; } cont = c->rcurr; // advance buffer. no matter what we're stopping. c->rbytes -= c->rlbytes; c->rcurr += c->rlbytes; c->sasl_started = false; // must end with \r\n // NB: I thought ASCII sets also worked with just \n, but according to // complete_nread_ascii only \r\n is valid. if (strncmp(cont + c->rlbytes - 2, "\r\n", 2) != 0) { out_string(c, "CLIENT_ERROR bad command line termination"); return 1; } // payload should be "user pass", so we can use the tokenizer. cont[c->rlbytes - 2] = '\0'; ntokens = tokenize_command(cont, tokens, MAX_TOKENS); if (ntokens < 3) { out_string(c, "CLIENT_ERROR bad authentication token format"); return 1; } if (authfile_check(tokens[0].value, tokens[1].value) == 1) { out_string(c, "STORED"); c->authenticated = true; c->try_read_command = try_read_command_ascii; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); } else { out_string(c, "CLIENT_ERROR authentication failure"); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } return 1; } static int try_read_command_ascii(conn *c) { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (ptr - c->rcurr > 100 || (strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); c->last_cmd_time = current_time; process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); return 1; } /* * read a UDP request. */ static enum try_read_result try_read_udp(conn *c) { int res; assert(c != NULL); c->request_addr_size = sizeof(c->request_addr); res = recvfrom(c->sfd, c->rbuf, c->rsize, 0, (struct sockaddr *)&c->request_addr, &c->request_addr_size); if (res > 8) { unsigned char *buf = (unsigned char *)c->rbuf; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* Beginning of UDP packet is the request ID; save it. */ c->request_id = buf[0] * 256 + buf[1]; /* If this is a multi-packet request, drop it. */ if (buf[4] != 0 || buf[5] != 1) { out_string(c, "SERVER_ERROR multi-packet request not supported"); return READ_NO_DATA_RECEIVED; } /* Don't care about any of the rest of the header. */ res -= 8; memmove(c->rbuf, c->rbuf + 8, res); c->rbytes = res; c->rcurr = c->rbuf; return READ_DATA_RECEIVED; } return READ_NO_DATA_RECEIVED; } /* * read from network as much as we can, handle buffer overflow and connection * close. * before reading, move the remaining incomplete fragment of a command * (if any) to the beginning of the buffer. * * To protect us from someone flooding a connection with bogus data causing * the connection to eat up all available memory, break out and start looking * at the data I've got after a number of reallocs... * * @return enum try_read_result */ static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose > 0) { fprintf(stderr, "Couldn't realloc input buffer\n"); } c->rbytes = 0; /* ignore what we read */ out_of_memory(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = c->read(c, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } static bool update_event(conn *c, const int new_flags) { assert(c != NULL); struct event_base *base = c->event.ev_base; if (c->ev_flags == new_flags) return true; if (event_del(&c->event) == -1) return false; event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = new_flags; if (event_add(&c->event, 0) == -1) return false; return true; } /* * Sets whether we are listening for new connections or not. */ void do_accept_new_conns(const bool do_accept) { conn *next; for (next = listen_conn; next; next = next->next) { if (do_accept) { update_event(next, EV_READ | EV_PERSIST); if (listen(next->sfd, settings.backlog) != 0) { perror("listen"); } } else { update_event(next, 0); if (listen(next->sfd, 0) != 0) { perror("listen"); } } } if (do_accept) { struct timeval maxconns_exited; uint64_t elapsed_us; gettimeofday(&maxconns_exited,NULL); STATS_LOCK(); elapsed_us = (maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000 + (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec); stats.time_in_listen_disabled_us += elapsed_us; stats_state.accepting_conns = true; STATS_UNLOCK(); } else { STATS_LOCK(); stats_state.accepting_conns = false; gettimeofday(&stats.maxconns_entered,NULL); stats.listen_disabled_num++; STATS_UNLOCK(); allow_new_conns = false; maxconns_handler(-42, 0, 0); } } /* * Transmit the next chunk of data from our list of msgbuf structures. * * Returns: * TRANSMIT_COMPLETE All done writing. * TRANSMIT_INCOMPLETE More data remaining to write. * TRANSMIT_SOFT_ERROR Can't write any more right now. * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing) */ static enum transmit_result transmit(conn *c) { assert(c != NULL); if (c->msgcurr < c->msgused && c->msglist[c->msgcurr].msg_iovlen == 0) { /* Finished writing the current msg; advance to the next. */ c->msgcurr++; } if (c->msgcurr < c->msgused) { ssize_t res; struct msghdr *m = &c->msglist[c->msgcurr]; res = c->sendmsg(c, m, 0); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_written += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* We've written some of the data. Remove the completed iovec entries from the list of pending writes. */ while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) { res -= m->msg_iov->iov_len; m->msg_iovlen--; m->msg_iov++; } /* Might have written just part of the last iovec entry; adjust it so the next write will do the rest. */ if (res > 0) { m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res; m->msg_iov->iov_len -= res; } return TRANSMIT_INCOMPLETE; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } return TRANSMIT_SOFT_ERROR; } /* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK, we have a real error, on which we close the connection */ if (settings.verbose > 0) perror("Failed to write, and not due to blocking"); if (IS_UDP(c->transport)) conn_set_state(c, conn_read); else conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } else { return TRANSMIT_COMPLETE; } } /* Does a looped read to fill data chunks */ /* TODO: restrict number of times this can loop. * Also, benchmark using readv's. */ static int read_into_chunked_item(conn *c) { int total = 0; int res; assert(c->rcurr != c->ritem); while (c->rlbytes > 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size == ch->used) { // FIXME: ch->next is currently always 0. remove this? if (ch->next) { c->ritem = (char *) ch->next; } else { /* Allocate next chunk. Binary protocol needs 2b for \r\n */ c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes + ((c->protocol == binary_prot) ? 2 : 0)); if (!c->ritem) { // We failed an allocation. Let caller handle cleanup. total = -2; break; } // ritem has new chunk, restart the loop. continue; //assert(c->rlbytes == 0); } } int unused = ch->size - ch->used; /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { total = 0; int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; tocopy = tocopy > unused ? unused : tocopy; if (c->ritem != c->rcurr) { memmove(ch->data + ch->used, c->rcurr, tocopy); } total += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; ch->used += tocopy; if (c->rlbytes == 0) { break; } } else { /* now try reading from the socket */ res = c->read(c, ch->data + ch->used, (unused > c->rlbytes ? c->rlbytes : unused)); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); ch->used += res; total += res; c->rlbytes -= res; } else { /* Reset total to the latest result so caller can handle it */ total = res; break; } } } /* At some point I will be able to ditch the \r\n from item storage and remove all of these kludges. The above binprot check ensures inline space for \r\n, but if we do exactly enough allocs there will be no additional chunk for \r\n. */ if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size - ch->used < 2) { c->ritem = (char *) do_item_alloc_chunk(ch, 2); if (!c->ritem) { total = -2; } } } return total; } static void drive_machine(conn *c) { bool stop = false; int sfd; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; #ifdef HAVE_ACCEPT4 static int use_accept4 = 1; #else static int use_accept4 = 0; #endif assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); #ifdef HAVE_ACCEPT4 if (use_accept4) { sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); } else { sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); } #else sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); #endif if (sfd == -1) { if (use_accept4 && errno == ENOSYS) { use_accept4 = 0; continue; } perror(use_accept4 ? "accept4()" : "accept()"); if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if (!use_accept4) { if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } } if (settings.maxconns_fast && stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { void *ssl_v = NULL; #ifdef TLS SSL *ssl = NULL; if (c->ssl_enabled) { assert(IS_TCP(c->transport) && settings.ssl_enabled); if (settings.ssl_ctx == NULL) { if (settings.verbose) { fprintf(stderr, "SSL context is not initialized\n"); } close(sfd); break; } SSL_LOCK(); ssl = SSL_new(settings.ssl_ctx); SSL_UNLOCK(); if (ssl == NULL) { if (settings.verbose) { fprintf(stderr, "Failed to created the SSL object\n"); } close(sfd); break; } SSL_set_fd(ssl, sfd); int ret = SSL_accept(ssl); if (ret < 0) { int err = SSL_get_error(ssl, ret); if (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) { if (settings.verbose) { fprintf(stderr, "SSL connection failed with error code : %d : %s\n", err, strerror(errno)); } close(sfd); break; } } } ssl_v = (void*) ssl; #endif dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, c->transport, ssl_v); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (c->try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* Check if rbytes < 0, to prevent crash */ if (c->rlbytes < 0) { if (settings.verbose) { fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes); } conn_set_state(c, conn_closing); break; } if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) { /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = c->read(c, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } } else { res = read_into_chunked_item(c); if (res > 0) break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* Memory allocation failure */ if (res == -2) { out_of_memory(c, "SERVER_ERROR Out of memory during read"); c->sbytes = c->rlbytes; c->write_and_go = conn_swallow; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes <= 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = c->read(c, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: #ifdef EXTSTORE /* have side IO's that must process before transmit() can run. * remove the connection from the worker thread and dispatch the * IO queue */ if (c->io_wrapleft) { assert(c->io_queued == false); assert(c->io_wraplist != NULL); // TODO: create proper state for this condition conn_set_state(c, conn_watch); event_del(&c->event); c->io_queued = true; extstore_submit(c->thread->storage, &c->io_wraplist->io); stop = true; break; } #endif if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { conn_release_items(c); /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_closed: /* This only happens if dormando is an idiot. */ abort(); break; case conn_watch: /* We handed off our connection to the logger thread. */ stop = true; break; case conn_max_state: assert(false); break; } } return; } void event_handler(const int fd, const short which, void *arg) { conn *c; c = (conn *)arg; assert(c != NULL); c->which = which; /* sanity */ if (fd != c->sfd) { if (settings.verbose > 0) fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n"); conn_close(c); return; } drive_machine(c); /* wait for next event */ return; } static int new_socket(struct addrinfo *ai) { int sfd; int flags; if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } /* * Sets a socket's send buffer size to the maximum allowed by the system. */ static void maximize_sndbuf(const int sfd) { socklen_t intsize = sizeof(int); int last_good = 0; int min, max, avg; int old_size; /* Start with the default size. */ if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) { if (settings.verbose > 0) perror("getsockopt(SO_SNDBUF)"); return; } /* Binary-search for the real maximum. */ min = old_size; max = MAX_SENDBUF_SIZE; while (min <= max) { avg = ((unsigned int)(min + max)) / 2; if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) { last_good = avg; min = avg + 1; } else { max = avg - 1; } } if (settings.verbose > 1) fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good); } /** * Create a socket and bind it to a specific port number * @param interface the interface to bind to * @param port the port number to bind to * @param transport the transport protocol (TCP / UDP) * @param portnumber_file A filepointer to write the port numbers to * when they are successfully added to the list of ports we * listen on. */ static int server_socket(const char *interface, int port, enum network_transport transport, FILE *portnumber_file, bool ssl_enabled) { int sfd; struct linger ling = {0, 0}; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; char port_buf[NI_MAXSERV]; int error; int success = 0; int flags =1; hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; if (port == -1) { port = 0; } snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { conn *listen_conn_add; if ((sfd = new_socket(next)) == -1) { /* getaddrinfo can return "junk" addresses, * we make sure at least one works before erroring. */ if (errno == EMFILE) { /* ...unless we're out of fds */ perror("server_socket"); exit(EX_OSERR); } continue; } #ifdef IPV6_V6ONLY if (next->ai_family == AF_INET6) { error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); if (error != 0) { perror("setsockopt"); close(sfd); continue; } } #endif setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (IS_UDP(transport)) { maximize_sndbuf(sfd); } else { error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); } if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } else { success++; if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); freeaddrinfo(ai); return 1; } if (portnumber_file != NULL && (next->ai_addr->sa_family == AF_INET || next->ai_addr->sa_family == AF_INET6)) { union { struct sockaddr_in in; struct sockaddr_in6 in6; } my_sockaddr; socklen_t len = sizeof(my_sockaddr); if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { if (next->ai_addr->sa_family == AF_INET) { fprintf(portnumber_file, "%s INET: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in.sin_port)); } else { fprintf(portnumber_file, "%s INET6: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in6.sin6_port)); } } } } if (IS_UDP(transport)) { int c; for (c = 0; c < settings.num_threads_per_udp; c++) { /* Allocate one UDP file descriptor per worker thread; * this allows "stats conns" to separately list multiple * parallel UDP requests in progress. * * The dispatch code round-robins new connection requests * among threads, so this is guaranteed to assign one * FD to each thread. */ int per_thread_fd; if (c == 0) { per_thread_fd = sfd; } else { per_thread_fd = dup(sfd); if (per_thread_fd < 0) { perror("Failed to duplicate file descriptor"); exit(EXIT_FAILURE); } } dispatch_conn_new(per_thread_fd, conn_read, EV_READ | EV_PERSIST, UDP_READ_BUFFER_SIZE, transport, NULL); } } else { if (!(listen_conn_add = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } #ifdef TLS listen_conn_add->ssl_enabled = ssl_enabled; #else assert(ssl_enabled == false); #endif listen_conn_add->next = listen_conn; listen_conn = listen_conn_add; } } freeaddrinfo(ai); /* Return zero iff we detected no errors in starting up connections */ return success == 0; } static int server_sockets(int port, enum network_transport transport, FILE *portnumber_file) { bool ssl_enabled = false; #ifdef TLS const char *notls = "notls"; ssl_enabled = settings.ssl_enabled; #endif if (settings.inter == NULL) { return server_socket(settings.inter, port, transport, portnumber_file, ssl_enabled); } else { // tokenize them and bind to each one of them.. char *b; int ret = 0; char *list = strdup(settings.inter); if (list == NULL) { fprintf(stderr, "Failed to allocate memory for parsing server interface string\n"); return 1; } for (char *p = strtok_r(list, ";,", &b); p != NULL; p = strtok_r(NULL, ";,", &b)) { int the_port = port; #ifdef TLS ssl_enabled = settings.ssl_enabled; // "notls" option is valid only when memcached is run with SSL enabled. if (strncmp(p, notls, strlen(notls)) == 0) { if (!settings.ssl_enabled) { fprintf(stderr, "'notls' option is valid only when SSL is enabled\n"); return 1; } ssl_enabled = false; p += strlen(notls) + 1; } #endif char *h = NULL; if (*p == '[') { // expecting it to be an IPv6 address enclosed in [] // i.e. RFC3986 style recommended by RFC5952 char *e = strchr(p, ']'); if (e == NULL) { fprintf(stderr, "Invalid IPV6 address: \"%s\"", p); free(list); return 1; } h = ++p; // skip the opening '[' *e = '\0'; p = ++e; // skip the closing ']' } char *s = strchr(p, ':'); if (s != NULL) { // If no more semicolons - attempt to treat as port number. // Otherwise the only valid option is an unenclosed IPv6 without port, until // of course there was an RFC3986 IPv6 address previously specified - // in such a case there is no good option, will just send it to fail as port number. if (strchr(s + 1, ':') == NULL || h != NULL) { *s = '\0'; ++s; if (!safe_strtol(s, &the_port)) { fprintf(stderr, "Invalid port number: \"%s\"", s); free(list); return 1; } } } if (h != NULL) p = h; if (strcmp(p, "*") == 0) { p = NULL; } ret |= server_socket(p, the_port, transport, portnumber_file, ssl_enabled); } free(list); return ret; } } static int new_socket_unix(void) { int sfd; int flags; if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } static int server_socket_unix(const char *path, int access_mask) { int sfd; struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags =1; int old_umask; if (!path) { return 1; } if ((sfd = new_socket_unix()) == -1) { return 1; } /* * Clean up a previous socket file if we left it around */ if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) unlink(path); } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); /* * the memset call clears nonstandard fields in some implementations * that otherwise mess things up. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask( ~(access_mask&0777)); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind()"); close(sfd); umask(old_umask); return 1; } umask(old_umask); if (listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); return 1; } if (!(listen_conn = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, local_transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } return 0; } /* * We keep the current time of day in a global variable that's updated by a * timer event. This saves us a bunch of time() system calls (we really only * need to get the time once a second, whereas there can be tens of thousands * of requests a second) and allows us to use server-start-relative timestamps * rather than absolute UNIX timestamps, a space savings on systems where * sizeof(time_t) > sizeof(unsigned int). */ volatile rel_time_t current_time; static struct event clockevent; /* libevent uses a monotonic clock when available for event scheduling. Aside * from jitter, simply ticking our internal timer here is accurate enough. * Note that users who are setting explicit dates for expiration times *must* * ensure their clocks are correct before starting memcached. */ static void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; static bool initialized = false; #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) static bool monotonic = false; static time_t monotonic_start; #endif if (initialized) { /* only delete the event if it's actually there. */ evtimer_del(&clockevent); } else { initialized = true; /* process_started is initialized to time() - 2. We initialize to 1 so * flush_all won't underflow during tests. */ #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { monotonic = true; monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2; } #endif } // While we're here, check for hash table expansion. // This function should be quick to avoid delaying the timer. assoc_start_expand(stats_state.curr_items); // also, if HUP'ed we need to do some maintenance. // for now that's just the authfile reload. if (settings.sig_hup) { settings.sig_hup = false; authfile_load(settings.auth_file); } evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) if (monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return; current_time = (rel_time_t) (ts.tv_sec - monotonic_start); return; } #endif { struct timeval tv; gettimeofday(&tv, NULL); current_time = (rel_time_t) (tv.tv_sec - process_started); } } static void usage(void) { printf(PACKAGE " " VERSION "\n"); printf("-p, --port=<num> TCP port to listen on (default: 11211)\n" "-U, --udp-port=<num> UDP port to listen on (default: 0, off)\n" "-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n" "-A, --enable-shutdown enable ascii \"shutdown\" command\n" "-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n" "-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n" #ifdef TLS " if TLS/SSL is enabled, 'notls' prefix can be used to\n" " disable for specific listeners (-l notls:<ip>:<port>) \n" #endif "-d, --daemon run as a daemon\n" "-r, --enable-coredumps maximize core file limit\n" "-u, --user=<user> assume identity of <username> (only when run as root)\n" "-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n" "-M, --disable-evictions return error on memory exhausted instead of evicting\n" "-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n" "-k, --lock-memory lock down all paged memory\n" "-v, --verbose verbose (print errors/warnings while in event loop)\n" "-vv very verbose (also print client commands/responses)\n" "-vvv extremely verbose (internal state transitions)\n" "-h, --help print this help and exit\n" "-i, --license print memcached and libevent license\n" "-V, --version print version and exit\n" "-P, --pidfile=<file> save PID in <file>, only used with -d option\n" "-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n" "-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n"); printf("-L, --enable-largepages try to use large memory pages (if available)\n"); printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n" " This is used for per-prefix stats reporting. The default is\n" " \":\" (colon). If this option is specified, stats collection\n" " is turned on automatically; if not, then it may be turned on\n" " by sending the \"stats detail on\" command to the server.\n"); printf("-t, --threads=<num> number of threads to use (default: 4)\n"); printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n" " requests processed per connection to prevent \n" " starvation (default: 20)\n"); printf("-C, --disable-cas disable use of CAS\n"); printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n"); printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n"); printf("-I, --max-item-size=<num> adjusts max item size\n" " (default: 1mb, min: 1k, max: 1024m)\n"); #ifdef ENABLE_SASL printf("-S, --enable-sasl turn on Sasl authentication\n"); #endif printf("-F, --disable-flush-all disable flush_all command\n"); printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n"); printf("-Y, --auth-file=<file> (EXPERIMENTAL) enable ASCII protocol authentication. format:\n" " user:pass\\nuser2:pass2\\n\n"); #ifdef TLS printf("-Z, --enable-ssl enable TLS/SSL\n"); #endif printf("-o, --extended comma separated list of extended options\n" " most options have a 'no_' prefix to disable\n" " - maxconns_fast: immediately close new connections after limit\n" " - hashpower: an integer multiplier for how large the hash\n" " table should be. normally grows at runtime.\n" " set based on \"STAT hash_power_level\"\n" " - tail_repair_time: time in seconds for how long to wait before\n" " forcefully killing LRU tail item.\n" " disabled by default; very dangerous option.\n" " - hash_algorithm: the hash table algorithm\n" " default is murmur3 hash. options: jenkins, murmur3\n" " - lru_crawler: enable LRU Crawler background thread\n" " - lru_crawler_sleep: microseconds to sleep between items\n" " default is 100.\n" " - lru_crawler_tocrawl: max items to crawl per slab per run\n" " default is 0 (unlimited)\n" " - lru_maintainer: enable new LRU system + background thread\n" " - hot_lru_pct: pct of slab memory to reserve for hot lru.\n" " (requires lru_maintainer)\n" " - warm_lru_pct: pct of slab memory to reserve for warm lru.\n" " (requires lru_maintainer)\n" " - hot_max_factor: items idle > cold lru age * drop from hot lru.\n" " - warm_max_factor: items idle > cold lru age * this drop from warm.\n" " - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n" " (requires lru_maintainer)\n" " - idle_timeout: timeout for idle connections\n" " - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n" " - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n" " - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n" " read by background thread, then written to watchers.\n" " - track_sizes: enable dynamic reports for 'stats sizes' command.\n" " - no_hashexpand: disables hash table expansion (dangerous)\n" " - modern: enables options which will be default in future.\n" " currently: nothing\n" " - no_modern: uses defaults of previous major version (1.4.x)\n" #ifdef HAVE_DROP_PRIVILEGES " - drop_privileges: enable dropping extra syscall privileges\n" " - no_drop_privileges: disable drop_privileges in case it causes issues with\n" " some customisation.\n" #ifdef MEMCACHED_DEBUG " - relaxed_privileges: Running tests requires extra privileges.\n" #endif #endif #ifdef EXTSTORE " - ext_path: file to write to for external storage.\n" " ie: ext_path=/mnt/d1/extstore:1G\n" " - ext_page_size: size in megabytes of storage pages.\n" " - ext_wbuf_size: size in megabytes of page write buffers.\n" " - ext_threads: number of IO threads to run.\n" " - ext_item_size: store items larger than this (bytes)\n" " - ext_item_age: store items idle at least this long\n" " - ext_low_ttl: consider TTLs lower than this specially\n" " - ext_drop_unread: don't re-write unread values during compaction\n" " - ext_recache_rate: recache an item every N accesses\n" " - ext_compact_under: compact when fewer than this many free pages\n" " - ext_drop_under: drop COLD items when fewer than this many free pages\n" " - ext_max_frag: max page fragmentation to tolerage\n" " - slab_automove_freeratio: ratio of memory to hold free as buffer.\n" " (see doc/storage.txt for more info)\n" #endif #ifdef TLS " - ssl_chain_cert: certificate chain file in PEM format\n" " - ssl_key: private key, if not part of the -ssl_chain_cert\n" " - ssl_keyformat: private key format (PEM, DER or ENGINE) PEM default\n" " - ssl_verify_mode: peer certificate verification mode, default is 0(None).\n" " valid values are 0(None), 1(Request), 2(Require)\n" " or 3(Once)\n" " - ssl_ciphers: specify cipher list to be used\n" " - ssl_ca_cert: PEM format file of acceptable client CA's\n" " - ssl_wbuf_size: size in kilobytes of per-connection SSL output buffer\n" #endif ); return; } static void usage_license(void) { printf(PACKAGE " " VERSION "\n\n"); printf( "Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are\n" "met:\n" "\n" " * Redistributions of source code must retain the above copyright\n" "notice, this list of conditions and the following disclaimer.\n" "\n" " * Redistributions in binary form must reproduce the above\n" "copyright notice, this list of conditions and the following disclaimer\n" "in the documentation and/or other materials provided with the\n" "distribution.\n" "\n" " * Neither the name of the Danga Interactive nor the names of its\n" "contributors may be used to endorse or promote products derived from\n" "this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" "\n" "\n" "This product includes software developed by Niels Provos.\n" "\n" "[ libevent ]\n" "\n" "Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions\n" "are met:\n" "1. Redistributions of source code must retain the above copyright\n" " notice, this list of conditions and the following disclaimer.\n" "2. Redistributions in binary form must reproduce the above copyright\n" " notice, this list of conditions and the following disclaimer in the\n" " documentation and/or other materials provided with the distribution.\n" "3. All advertising materials mentioning features or use of this software\n" " must display the following acknowledgement:\n" " This product includes software developed by Niels Provos.\n" "4. The name of the author may not be used to endorse or promote products\n" " derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ); return; } static void save_pid(const char *pid_file) { FILE *fp; if (access(pid_file, F_OK) == 0) { if ((fp = fopen(pid_file, "r")) != NULL) { char buffer[1024]; if (fgets(buffer, sizeof(buffer), fp) != NULL) { unsigned int pid; if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) { fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid); } } fclose(fp); } } /* Create the pid file first with a temporary name, then * atomically move the file to the real name to avoid a race with * another process opening the file to read the pid, but finding * it empty. */ char tmp_pid_file[1024]; snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file); if ((fp = fopen(tmp_pid_file, "w")) == NULL) { vperror("Could not open the pid file %s for writing", tmp_pid_file); return; } fprintf(fp,"%ld\n", (long)getpid()); if (fclose(fp) == -1) { vperror("Could not close the pid file %s", tmp_pid_file); } if (rename(tmp_pid_file, pid_file) != 0) { vperror("Could not rename the pid file from %s to %s", tmp_pid_file, pid_file); } } static void remove_pidfile(const char *pid_file) { if (pid_file == NULL) return; if (unlink(pid_file) != 0) { vperror("Could not remove the pid file %s", pid_file); } } static void sig_handler(const int sig) { printf("Signal handled: %s.\n", strsignal(sig)); exit(EXIT_SUCCESS); } static void sighup_handler(const int sig) { settings.sig_hup = true; } #ifndef HAVE_SIGIGNORE static int sigignore(int sig) { struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 }; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } #endif /* * On systems that supports multiple page sizes we may reduce the * number of TLB-misses by using the biggest available page size */ static int enable_large_pages(void) { #if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL) int ret = -1; size_t sizes[32]; int avail = getpagesizes(sizes, 32); if (avail != -1) { size_t max = sizes[0]; struct memcntl_mha arg = {0}; int ii; for (ii = 1; ii < avail; ++ii) { if (max < sizes[ii]) { max = sizes[ii]; } } arg.mha_flags = 0; arg.mha_pagesize = max; arg.mha_cmd = MHA_MAPSIZE_BSSBRK; if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) { fprintf(stderr, "Failed to set large pages: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } else { ret = 0; } } else { fprintf(stderr, "Failed to get supported pagesizes: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } return ret; #elif defined(__linux__) && defined(MADV_HUGEPAGE) /* check if transparent hugepages is compiled into the kernel */ struct stat st; int ret = stat("/sys/kernel/mm/transparent_hugepage/enabled", &st); if (ret || !(st.st_mode & S_IFREG)) { fprintf(stderr, "Transparent huge pages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #elif defined(__FreeBSD__) int spages; size_t spagesl = sizeof(spages); if (sysctlbyname("vm.pmap.pg_ps_enabled", &spages, &spagesl, NULL, 0) != 0) { fprintf(stderr, "Could not evaluate the presence of superpages features."); return -1; } if (spages != 1) { fprintf(stderr, "Superpages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #else return -1; #endif } /** * Do basic sanity check of the runtime environment * @return true if no errors found, false if we can't use this env */ static bool sanitycheck(void) { /* One of our biggest problems is old and bogus libevents */ const char *ever = event_get_version(); if (ever != NULL) { if (strncmp(ever, "1.", 2) == 0) { /* Require at least 1.3 (that's still a couple of years old) */ if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) { fprintf(stderr, "You are using libevent %s.\nPlease upgrade to" " a more recent version (1.3 or newer)\n", event_get_version()); return false; } } } return true; } static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) { char *b = NULL; uint32_t size = 0; int i = 0; uint32_t last_size = 0; if (strlen(s) < 1) return false; for (char *p = strtok_r(s, "-", &b); p != NULL; p = strtok_r(NULL, "-", &b)) { if (!safe_strtoul(p, &size) || size < settings.chunk_size || size > settings.slab_chunk_size_max) { fprintf(stderr, "slab size %u is out of valid range\n", size); return false; } if (last_size >= size) { fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size); return false; } if (size <= last_size + CHUNK_ALIGN_BYTES) { fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n", size, CHUNK_ALIGN_BYTES); return false; } slab_sizes[i++] = size; last_size = size; if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) { fprintf(stderr, "too many slab classes specified\n"); return false; } } slab_sizes[i] = 0; return true; } int main (int argc, char **argv) { int c; bool lock_memory = false; bool do_daemonize = false; bool preallocate = false; int maxcore = 0; char *username = NULL; char *pid_file = NULL; struct passwd *pw; struct rlimit rlim; char *buf; char unit = '\0'; int size_max = 0; int retval = EXIT_SUCCESS; bool protocol_specified = false; bool tcp_specified = false; bool udp_specified = false; bool start_lru_maintainer = true; bool start_lru_crawler = true; bool start_assoc_maint = true; enum hashfunc_type hash_type = MURMUR3_HASH; uint32_t tocrawl; uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES]; bool use_slab_sizes = false; char *slab_sizes_unparsed = NULL; bool slab_chunk_size_changed = false; #ifdef EXTSTORE void *storage = NULL; struct extstore_conf_file *storage_file = NULL; struct extstore_conf ext_cf; #endif char *subopts, *subopts_orig; char *subopts_value; enum { MAXCONNS_FAST = 0, HASHPOWER_INIT, NO_HASHEXPAND, SLAB_REASSIGN, SLAB_AUTOMOVE, SLAB_AUTOMOVE_RATIO, SLAB_AUTOMOVE_WINDOW, TAIL_REPAIR_TIME, HASH_ALGORITHM, LRU_CRAWLER, LRU_CRAWLER_SLEEP, LRU_CRAWLER_TOCRAWL, LRU_MAINTAINER, HOT_LRU_PCT, WARM_LRU_PCT, HOT_MAX_FACTOR, WARM_MAX_FACTOR, TEMPORARY_TTL, IDLE_TIMEOUT, WATCHER_LOGBUF_SIZE, WORKER_LOGBUF_SIZE, SLAB_SIZES, SLAB_CHUNK_MAX, TRACK_SIZES, NO_INLINE_ASCII_RESP, MODERN, NO_MODERN, NO_CHUNKED_ITEMS, NO_SLAB_REASSIGN, NO_SLAB_AUTOMOVE, NO_MAXCONNS_FAST, INLINE_ASCII_RESP, NO_LRU_CRAWLER, NO_LRU_MAINTAINER, NO_DROP_PRIVILEGES, DROP_PRIVILEGES, #ifdef TLS SSL_CERT, SSL_KEY, SSL_VERIFY_MODE, SSL_KEYFORM, SSL_CIPHERS, SSL_CA_CERT, SSL_WBUF_SIZE, #endif #ifdef MEMCACHED_DEBUG RELAXED_PRIVILEGES, #endif #ifdef EXTSTORE EXT_PAGE_SIZE, EXT_WBUF_SIZE, EXT_THREADS, EXT_IO_DEPTH, EXT_PATH, EXT_ITEM_SIZE, EXT_ITEM_AGE, EXT_LOW_TTL, EXT_RECACHE_RATE, EXT_COMPACT_UNDER, EXT_DROP_UNDER, EXT_MAX_FRAG, EXT_DROP_UNREAD, SLAB_AUTOMOVE_FREERATIO, #endif }; char *const subopts_tokens[] = { [MAXCONNS_FAST] = "maxconns_fast", [HASHPOWER_INIT] = "hashpower", [NO_HASHEXPAND] = "no_hashexpand", [SLAB_REASSIGN] = "slab_reassign", [SLAB_AUTOMOVE] = "slab_automove", [SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio", [SLAB_AUTOMOVE_WINDOW] = "slab_automove_window", [TAIL_REPAIR_TIME] = "tail_repair_time", [HASH_ALGORITHM] = "hash_algorithm", [LRU_CRAWLER] = "lru_crawler", [LRU_CRAWLER_SLEEP] = "lru_crawler_sleep", [LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl", [LRU_MAINTAINER] = "lru_maintainer", [HOT_LRU_PCT] = "hot_lru_pct", [WARM_LRU_PCT] = "warm_lru_pct", [HOT_MAX_FACTOR] = "hot_max_factor", [WARM_MAX_FACTOR] = "warm_max_factor", [TEMPORARY_TTL] = "temporary_ttl", [IDLE_TIMEOUT] = "idle_timeout", [WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size", [WORKER_LOGBUF_SIZE] = "worker_logbuf_size", [SLAB_SIZES] = "slab_sizes", [SLAB_CHUNK_MAX] = "slab_chunk_max", [TRACK_SIZES] = "track_sizes", [NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp", [MODERN] = "modern", [NO_MODERN] = "no_modern", [NO_CHUNKED_ITEMS] = "no_chunked_items", [NO_SLAB_REASSIGN] = "no_slab_reassign", [NO_SLAB_AUTOMOVE] = "no_slab_automove", [NO_MAXCONNS_FAST] = "no_maxconns_fast", [INLINE_ASCII_RESP] = "inline_ascii_resp", [NO_LRU_CRAWLER] = "no_lru_crawler", [NO_LRU_MAINTAINER] = "no_lru_maintainer", [NO_DROP_PRIVILEGES] = "no_drop_privileges", [DROP_PRIVILEGES] = "drop_privileges", #ifdef TLS [SSL_CERT] = "ssl_chain_cert", [SSL_KEY] = "ssl_key", [SSL_VERIFY_MODE] = "ssl_verify_mode", [SSL_KEYFORM] = "ssl_keyformat", [SSL_CIPHERS] = "ssl_ciphers", [SSL_CA_CERT] = "ssl_ca_cert", [SSL_WBUF_SIZE] = "ssl_wbuf_size", #endif #ifdef MEMCACHED_DEBUG [RELAXED_PRIVILEGES] = "relaxed_privileges", #endif #ifdef EXTSTORE [EXT_PAGE_SIZE] = "ext_page_size", [EXT_WBUF_SIZE] = "ext_wbuf_size", [EXT_THREADS] = "ext_threads", [EXT_IO_DEPTH] = "ext_io_depth", [EXT_PATH] = "ext_path", [EXT_ITEM_SIZE] = "ext_item_size", [EXT_ITEM_AGE] = "ext_item_age", [EXT_LOW_TTL] = "ext_low_ttl", [EXT_RECACHE_RATE] = "ext_recache_rate", [EXT_COMPACT_UNDER] = "ext_compact_under", [EXT_DROP_UNDER] = "ext_drop_under", [EXT_MAX_FRAG] = "ext_max_frag", [EXT_DROP_UNREAD] = "ext_drop_unread", [SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio", #endif NULL }; if (!sanitycheck()) { return EX_OSERR; } /* handle SIGINT, SIGTERM */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sighup_handler); /* init settings */ settings_init(); #ifdef EXTSTORE settings.ext_item_size = 512; settings.ext_item_age = UINT_MAX; settings.ext_low_ttl = 0; settings.ext_recache_rate = 2000; settings.ext_max_frag = 0.8; settings.ext_drop_unread = false; settings.ext_wbuf_size = 1024 * 1024 * 4; settings.ext_compact_under = 0; settings.ext_drop_under = 0; settings.slab_automove_freeratio = 0.01; ext_cf.page_size = 1024 * 1024 * 64; ext_cf.wbuf_size = settings.ext_wbuf_size; ext_cf.io_threadcount = 1; ext_cf.io_depth = 1; ext_cf.page_buckets = 4; ext_cf.wbuf_count = ext_cf.page_buckets; #endif /* Run regardless of initializing it later */ init_lru_maintainer(); /* set stderr non-buffering (for running under, say, daemontools) */ setbuf(stderr, NULL); char *shortopts = "a:" /* access mask for unix socket */ "A" /* enable admin shutdown command */ "Z" /* enable SSL */ "p:" /* TCP port number to listen on */ "s:" /* unix socket path to listen on */ "U:" /* UDP port number to listen on */ "m:" /* max memory to use for items in megabytes */ "M" /* return error on memory exhausted */ "c:" /* max simultaneous connections */ "k" /* lock down all paged memory */ "hiV" /* help, licence info, version */ "r" /* maximize core file limit */ "v" /* verbose */ "d" /* daemon mode */ "l:" /* interface to listen on */ "u:" /* user identity to run as */ "P:" /* save PID in file */ "f:" /* factor? */ "n:" /* minimum space allocated for key+value+flags */ "t:" /* threads */ "D:" /* prefix delimiter? */ "L" /* Large memory pages */ "R:" /* max requests per event */ "C" /* Disable use of CAS */ "b:" /* backlog queue limit */ "B:" /* Binding protocol */ "I:" /* Max item size */ "S" /* Sasl ON */ "F" /* Disable flush_all */ "X" /* Disable dump commands */ "Y:" /* Enable token auth */ "o:" /* Extended generic options */ ; /* process arguments */ #ifdef HAVE_GETOPT_LONG const struct option longopts[] = { {"unix-mask", required_argument, 0, 'a'}, {"enable-shutdown", no_argument, 0, 'A'}, {"enable-ssl", no_argument, 0, 'Z'}, {"port", required_argument, 0, 'p'}, {"unix-socket", required_argument, 0, 's'}, {"udp-port", required_argument, 0, 'U'}, {"memory-limit", required_argument, 0, 'm'}, {"disable-evictions", no_argument, 0, 'M'}, {"conn-limit", required_argument, 0, 'c'}, {"lock-memory", no_argument, 0, 'k'}, {"help", no_argument, 0, 'h'}, {"license", no_argument, 0, 'i'}, {"version", no_argument, 0, 'V'}, {"enable-coredumps", no_argument, 0, 'r'}, {"verbose", optional_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"listen", required_argument, 0, 'l'}, {"user", required_argument, 0, 'u'}, {"pidfile", required_argument, 0, 'P'}, {"slab-growth-factor", required_argument, 0, 'f'}, {"slab-min-size", required_argument, 0, 'n'}, {"threads", required_argument, 0, 't'}, {"enable-largepages", no_argument, 0, 'L'}, {"max-reqs-per-event", required_argument, 0, 'R'}, {"disable-cas", no_argument, 0, 'C'}, {"listen-backlog", required_argument, 0, 'b'}, {"protocol", required_argument, 0, 'B'}, {"max-item-size", required_argument, 0, 'I'}, {"enable-sasl", no_argument, 0, 'S'}, {"disable-flush-all", no_argument, 0, 'F'}, {"disable-dumping", no_argument, 0, 'X'}, {"auth-file", required_argument, 0, 'Y'}, {"extended", required_argument, 0, 'o'}, {0, 0, 0, 0} }; int optindex; while (-1 != (c = getopt_long(argc, argv, shortopts, longopts, &optindex))) { #else while (-1 != (c = getopt(argc, argv, shortopts))) { #endif switch (c) { case 'A': /* enables "shutdown" command */ settings.shutdown_command = true; break; case 'Z': /* enable secure communication*/ #ifdef TLS settings.ssl_enabled = true; #else fprintf(stderr, "This server is not built with TLS support.\n"); exit(EX_USAGE); #endif break; case 'a': /* access for unix domain socket, as octal mask (like chmod)*/ settings.access= strtol(optarg,NULL,8); break; case 'U': settings.udpport = atoi(optarg); udp_specified = true; break; case 'p': settings.port = atoi(optarg); tcp_specified = true; break; case 's': settings.socketpath = optarg; break; case 'm': settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024; break; case 'M': settings.evict_to_free = 0; break; case 'c': settings.maxconns = atoi(optarg); if (settings.maxconns <= 0) { fprintf(stderr, "Maximum connections must be greater than 0\n"); return 1; } break; case 'h': usage(); exit(EXIT_SUCCESS); case 'i': usage_license(); exit(EXIT_SUCCESS); case 'V': printf(PACKAGE " " VERSION "\n"); exit(EXIT_SUCCESS); case 'k': lock_memory = true; break; case 'v': settings.verbose++; break; case 'l': if (settings.inter != NULL) { if (strstr(settings.inter, optarg) != NULL) { break; } size_t len = strlen(settings.inter) + strlen(optarg) + 2; char *p = malloc(len); if (p == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } snprintf(p, len, "%s,%s", settings.inter, optarg); free(settings.inter); settings.inter = p; } else { settings.inter= strdup(optarg); } break; case 'd': do_daemonize = true; break; case 'r': maxcore = 1; break; case 'R': settings.reqs_per_event = atoi(optarg); if (settings.reqs_per_event == 0) { fprintf(stderr, "Number of requests per event must be greater than 0\n"); return 1; } break; case 'u': username = optarg; break; case 'P': pid_file = optarg; break; case 'f': settings.factor = atof(optarg); if (settings.factor <= 1.0) { fprintf(stderr, "Factor must be greater than 1\n"); return 1; } break; case 'n': settings.chunk_size = atoi(optarg); if (settings.chunk_size == 0) { fprintf(stderr, "Chunk size must be greater than 0\n"); return 1; } break; case 't': settings.num_threads = atoi(optarg); if (settings.num_threads <= 0) { fprintf(stderr, "Number of threads must be greater than 0\n"); return 1; } /* There're other problems when you get above 64 threads. * In the future we should portably detect # of cores for the * default. */ if (settings.num_threads > 64) { fprintf(stderr, "WARNING: Setting a high number of worker" "threads is not recommended.\n" " Set this value to the number of cores in" " your machine or less.\n"); } break; case 'D': if (! optarg || ! optarg[0]) { fprintf(stderr, "No delimiter specified\n"); return 1; } settings.prefix_delimiter = optarg[0]; settings.detail_enabled = 1; break; case 'L' : if (enable_large_pages() == 0) { preallocate = true; } else { fprintf(stderr, "Cannot enable large pages on this system\n" "(There is no support as of this version)\n"); return 1; } break; case 'C' : settings.use_cas = false; break; case 'b' : settings.backlog = atoi(optarg); break; case 'B': protocol_specified = true; if (strcmp(optarg, "auto") == 0) { settings.binding_protocol = negotiating_prot; } else if (strcmp(optarg, "binary") == 0) { settings.binding_protocol = binary_prot; } else if (strcmp(optarg, "ascii") == 0) { settings.binding_protocol = ascii_prot; } else { fprintf(stderr, "Invalid value for binding protocol: %s\n" " -- should be one of auto, binary, or ascii\n", optarg); exit(EX_USAGE); } break; case 'I': buf = strdup(optarg); unit = buf[strlen(buf)-1]; if (unit == 'k' || unit == 'm' || unit == 'K' || unit == 'M') { buf[strlen(buf)-1] = '\0'; size_max = atoi(buf); if (unit == 'k' || unit == 'K') size_max *= 1024; if (unit == 'm' || unit == 'M') size_max *= 1024 * 1024; settings.item_size_max = size_max; } else { settings.item_size_max = atoi(buf); } free(buf); break; case 'S': /* set Sasl authentication to true. Default is false */ #ifndef ENABLE_SASL fprintf(stderr, "This server is not built with SASL support.\n"); exit(EX_USAGE); #endif settings.sasl = true; break; case 'F' : settings.flush_enabled = false; break; case 'X' : settings.dump_enabled = false; break; case 'Y' : // dupe the file path now just in case the options get mangled. settings.auth_file = strdup(optarg); break; case 'o': /* It's sub-opts time! */ subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */ while (*subopts != '\0') { switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) { case MAXCONNS_FAST: settings.maxconns_fast = true; break; case HASHPOWER_INIT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for hashpower\n"); return 1; } settings.hashpower_init = atoi(subopts_value); if (settings.hashpower_init < 12) { fprintf(stderr, "Initial hashtable multiplier of %d is too low\n", settings.hashpower_init); return 1; } else if (settings.hashpower_init > 32) { fprintf(stderr, "Initial hashtable multiplier of %d is too high\n" "Choose a value based on \"STAT hash_power_level\" from a running instance\n", settings.hashpower_init); return 1; } break; case NO_HASHEXPAND: start_assoc_maint = false; break; case SLAB_REASSIGN: settings.slab_reassign = true; break; case SLAB_AUTOMOVE: if (subopts_value == NULL) { settings.slab_automove = 1; break; } settings.slab_automove = atoi(subopts_value); if (settings.slab_automove < 0 || settings.slab_automove > 2) { fprintf(stderr, "slab_automove must be between 0 and 2\n"); return 1; } break; case SLAB_AUTOMOVE_RATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_ratio argument\n"); return 1; } settings.slab_automove_ratio = atof(subopts_value); if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) { fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n"); return 1; } break; case SLAB_AUTOMOVE_WINDOW: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_window argument\n"); return 1; } settings.slab_automove_window = atoi(subopts_value); if (settings.slab_automove_window < 3) { fprintf(stderr, "slab_automove_window must be > 2\n"); return 1; } break; case TAIL_REPAIR_TIME: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for tail_repair_time\n"); return 1; } settings.tail_repair_time = atoi(subopts_value); if (settings.tail_repair_time < 10) { fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n"); return 1; } break; case HASH_ALGORITHM: if (subopts_value == NULL) { fprintf(stderr, "Missing hash_algorithm argument\n"); return 1; }; if (strcmp(subopts_value, "jenkins") == 0) { hash_type = JENKINS_HASH; } else if (strcmp(subopts_value, "murmur3") == 0) { hash_type = MURMUR3_HASH; } else { fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n"); return 1; } break; case LRU_CRAWLER: start_lru_crawler = true; break; case LRU_CRAWLER_SLEEP: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_sleep value\n"); return 1; } settings.lru_crawler_sleep = atoi(subopts_value); if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) { fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n"); return 1; } break; case LRU_CRAWLER_TOCRAWL: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_tocrawl value\n"); return 1; } if (!safe_strtoul(subopts_value, &tocrawl)) { fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n"); return 1; } settings.lru_crawler_tocrawl = tocrawl; break; case LRU_MAINTAINER: start_lru_maintainer = true; settings.lru_segmented = true; break; case HOT_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_lru_pct argument\n"); return 1; } settings.hot_lru_pct = atoi(subopts_value); if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) { fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n"); return 1; } break; case WARM_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_lru_pct argument\n"); return 1; } settings.warm_lru_pct = atoi(subopts_value); if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) { fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n"); return 1; } break; case HOT_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_max_factor argument\n"); return 1; } settings.hot_max_factor = atof(subopts_value); if (settings.hot_max_factor <= 0) { fprintf(stderr, "hot_max_factor must be > 0\n"); return 1; } break; case WARM_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_max_factor argument\n"); return 1; } settings.warm_max_factor = atof(subopts_value); if (settings.warm_max_factor <= 0) { fprintf(stderr, "warm_max_factor must be > 0\n"); return 1; } break; case TEMPORARY_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing temporary_ttl argument\n"); return 1; } settings.temp_lru = true; settings.temporary_ttl = atoi(subopts_value); break; case IDLE_TIMEOUT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for idle_timeout\n"); return 1; } settings.idle_timeout = atoi(subopts_value); break; case WATCHER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing watcher_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) { fprintf(stderr, "could not parse argument to watcher_logbuf_size\n"); return 1; } settings.logger_watcher_buf_size *= 1024; /* kilobytes */ break; case WORKER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing worker_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) { fprintf(stderr, "could not parse argument to worker_logbuf_size\n"); return 1; } settings.logger_buf_size *= 1024; /* kilobytes */ case SLAB_SIZES: slab_sizes_unparsed = strdup(subopts_value); break; case SLAB_CHUNK_MAX: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_chunk_max argument\n"); } if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) { fprintf(stderr, "could not parse argument to slab_chunk_max\n"); } slab_chunk_size_changed = true; break; case TRACK_SIZES: item_stats_sizes_init(); break; case NO_INLINE_ASCII_RESP: break; case INLINE_ASCII_RESP: break; case NO_CHUNKED_ITEMS: settings.slab_chunk_size_max = settings.slab_page_size; break; case NO_SLAB_REASSIGN: settings.slab_reassign = false; break; case NO_SLAB_AUTOMOVE: settings.slab_automove = 0; break; case NO_MAXCONNS_FAST: settings.maxconns_fast = false; break; case NO_LRU_CRAWLER: settings.lru_crawler = false; start_lru_crawler = false; break; case NO_LRU_MAINTAINER: start_lru_maintainer = false; settings.lru_segmented = false; break; #ifdef TLS case SSL_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_chain_cert argument\n"); return 1; } settings.ssl_chain_cert = strdup(subopts_value); break; case SSL_KEY: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_key argument\n"); return 1; } settings.ssl_key = strdup(subopts_value); break; case SSL_VERIFY_MODE: { if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_verify_mode argument\n"); return 1; } int verify = 0; if (!safe_strtol(subopts_value, &verify)) { fprintf(stderr, "could not parse argument to ssl_verify_mode\n"); return 1; } switch(verify) { case 0: settings.ssl_verify_mode = SSL_VERIFY_NONE; break; case 1: settings.ssl_verify_mode = SSL_VERIFY_PEER; break; case 2: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; break; case 3: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; break; default: fprintf(stderr, "Invalid ssl_verify_mode. Use help to see valid options.\n"); return 1; } break; } case SSL_KEYFORM: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_keyformat argument\n"); return 1; } if (!safe_strtol(subopts_value, &settings.ssl_keyformat)) { fprintf(stderr, "could not parse argument to ssl_keyformat\n"); return 1; } break; case SSL_CIPHERS: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ciphers argument\n"); return 1; } settings.ssl_ciphers = strdup(subopts_value); break; case SSL_CA_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ca_cert argument\n"); return 1; } settings.ssl_ca_cert = strdup(subopts_value); break; case SSL_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ssl_wbuf_size)) { fprintf(stderr, "could not parse argument to ssl_wbuf_size\n"); return 1; } settings.ssl_wbuf_size *= 1024; /* kilobytes */ break; #endif #ifdef EXTSTORE case EXT_PAGE_SIZE: if (storage_file) { fprintf(stderr, "Must specify ext_page_size before any ext_path arguments\n"); return 1; } if (subopts_value == NULL) { fprintf(stderr, "Missing ext_page_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.page_size)) { fprintf(stderr, "could not parse argument to ext_page_size\n"); return 1; } ext_cf.page_size *= 1024 * 1024; /* megabytes */ break; case EXT_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) { fprintf(stderr, "could not parse argument to ext_wbuf_size\n"); return 1; } ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */ settings.ext_wbuf_size = ext_cf.wbuf_size; break; case EXT_THREADS: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_threads argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) { fprintf(stderr, "could not parse argument to ext_threads\n"); return 1; } break; case EXT_IO_DEPTH: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_io_depth argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) { fprintf(stderr, "could not parse argument to ext_io_depth\n"); return 1; } break; case EXT_ITEM_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_size)) { fprintf(stderr, "could not parse argument to ext_item_size\n"); return 1; } break; case EXT_ITEM_AGE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_age argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_age)) { fprintf(stderr, "could not parse argument to ext_item_age\n"); return 1; } break; case EXT_LOW_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_low_ttl argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) { fprintf(stderr, "could not parse argument to ext_low_ttl\n"); return 1; } break; case EXT_RECACHE_RATE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_recache_rate argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) { fprintf(stderr, "could not parse argument to ext_recache_rate\n"); return 1; } break; case EXT_COMPACT_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_compact_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) { fprintf(stderr, "could not parse argument to ext_compact_under\n"); return 1; } break; case EXT_DROP_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_drop_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) { fprintf(stderr, "could not parse argument to ext_drop_under\n"); return 1; } break; case EXT_MAX_FRAG: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_max_frag argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.ext_max_frag)) { fprintf(stderr, "could not parse argument to ext_max_frag\n"); return 1; } break; case SLAB_AUTOMOVE_FREERATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_freeratio argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) { fprintf(stderr, "could not parse argument to slab_automove_freeratio\n"); return 1; } break; case EXT_DROP_UNREAD: settings.ext_drop_unread = true; break; case EXT_PATH: if (subopts_value) { struct extstore_conf_file *tmp = storage_conf_parse(subopts_value, ext_cf.page_size); if (tmp == NULL) { fprintf(stderr, "failed to parse ext_path argument\n"); return 1; } if (storage_file != NULL) { tmp->next = storage_file; } storage_file = tmp; } else { fprintf(stderr, "missing argument to ext_path, ie: ext_path=/d/file:5G\n"); return 1; } break; #endif case MODERN: /* currently no new defaults */ break; case NO_MODERN: if (!slab_chunk_size_changed) { settings.slab_chunk_size_max = settings.slab_page_size; } settings.slab_reassign = false; settings.slab_automove = 0; settings.maxconns_fast = false; settings.lru_segmented = false; hash_type = JENKINS_HASH; start_lru_crawler = false; start_lru_maintainer = false; break; case NO_DROP_PRIVILEGES: settings.drop_privileges = false; break; case DROP_PRIVILEGES: settings.drop_privileges = true; break; #ifdef MEMCACHED_DEBUG case RELAXED_PRIVILEGES: settings.relaxed_privileges = true; break; #endif default: printf("Illegal suboption \"%s\"\n", subopts_value); return 1; } } free(subopts_orig); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings.item_size_max < 1024) { fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n"); exit(EX_USAGE); } if (settings.item_size_max > (settings.maxbytes / 2)) { fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n"); exit(EX_USAGE); } if (settings.item_size_max > (1024 * 1024 * 1024)) { fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n"); exit(EX_USAGE); } if (settings.item_size_max > 1024 * 1024) { if (!slab_chunk_size_changed) { // Ideal new default is 16k, but needs stitching. settings.slab_chunk_size_max = settings.slab_page_size / 2; } } if (settings.slab_chunk_size_max > settings.item_size_max) { fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n", settings.slab_chunk_size_max, settings.item_size_max); exit(EX_USAGE); } if (settings.item_size_max % settings.slab_chunk_size_max != 0) { fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n", settings.item_size_max, settings.slab_chunk_size_max); exit(EX_USAGE); } if (settings.slab_page_size % settings.slab_chunk_size_max != 0) { fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n", settings.slab_chunk_size_max, settings.slab_page_size); exit(EX_USAGE); } #ifdef EXTSTORE if (storage_file) { if (settings.item_size_max > ext_cf.wbuf_size) { fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n", settings.item_size_max, ext_cf.wbuf_size); exit(EX_USAGE); } if (settings.udpport) { fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n"); exit(EX_USAGE); } } #endif // Reserve this for the new default. If factor size hasn't changed, use // new default. /*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) { settings.factor = 1.08; }*/ if (slab_sizes_unparsed != NULL) { if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) { use_slab_sizes = true; } else { exit(EX_USAGE); } } if (settings.hot_lru_pct + settings.warm_lru_pct > 80) { fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n"); exit(EX_USAGE); } if (settings.temp_lru && !start_lru_maintainer) { fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n"); exit(EX_USAGE); } if (hash_init(hash_type) != 0) { fprintf(stderr, "Failed to initialize hash_algorithm!\n"); exit(EX_USAGE); } /* * Use one workerthread to serve each UDP port if the user specified * multiple ports */ if (settings.inter != NULL && strchr(settings.inter, ',')) { settings.num_threads_per_udp = 1; } else { settings.num_threads_per_udp = settings.num_threads; } if (settings.sasl) { if (!protocol_specified) { settings.binding_protocol = binary_prot; } else { if (settings.binding_protocol != binary_prot) { fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n"); exit(EX_USAGE); } } } if (settings.auth_file) { if (!protocol_specified) { settings.binding_protocol = ascii_prot; } else { if (settings.binding_protocol != ascii_prot) { fprintf(stderr, "ERROR: You cannot allow the BINARY protocol while using ascii authentication tokens.\n"); exit(EX_USAGE); } } } if (udp_specified && settings.udpport != 0 && !tcp_specified) { settings.port = settings.udpport; } #ifdef TLS /* * Setup SSL if enabled */ if (settings.ssl_enabled) { if (!settings.port) { fprintf(stderr, "ERROR: You cannot enable SSL without a TCP port.\n"); exit(EX_USAGE); } // openssl init methods. SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); // Initiate the SSL context. ssl_init(); } #endif if (maxcore != 0) { struct rlimit rlim_new; /* * First try raising to infinity; if that fails, try bringing * the soft limit to the hard. */ if (getrlimit(RLIMIT_CORE, &rlim) == 0) { rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) { /* failed. try raising just to the old max */ rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max; (void)setrlimit(RLIMIT_CORE, &rlim_new); } } /* * getrlimit again to see what we ended up with. Only fail if * the soft limit ends up 0, because then no core files will be * created at all. */ if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) { fprintf(stderr, "failed to ensure corefile creation\n"); exit(EX_OSERR); } } /* * If needed, increase rlimits to allow as many connections * as needed. */ if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to getrlimit number of files\n"); exit(EX_OSERR); } else { rlim.rlim_cur = settings.maxconns; rlim.rlim_max = settings.maxconns; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n"); exit(EX_OSERR); } } /* lose root privileges if we have them */ if (getuid() == 0 || geteuid() == 0) { if (username == 0 || *username == '\0') { fprintf(stderr, "can't run as root without the -u switch\n"); exit(EX_USAGE); } if ((pw = getpwnam(username)) == 0) { fprintf(stderr, "can't find the user %s to switch to\n", username); exit(EX_NOUSER); } if (setgroups(0, NULL) < 0) { fprintf(stderr, "failed to drop supplementary groups\n"); exit(EX_OSERR); } if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { fprintf(stderr, "failed to assume identity of user %s\n", username); exit(EX_OSERR); } } /* Initialize Sasl if -S was specified */ if (settings.sasl) { init_sasl(); } /* daemonize if requested */ /* if we want to ensure our ability to dump core, don't chdir to / */ if (do_daemonize) { if (sigignore(SIGHUP) == -1) { perror("Failed to ignore SIGHUP"); } if (daemonize(maxcore, settings.verbose) == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } /* lock paged memory if needed */ if (lock_memory) { #ifdef HAVE_MLOCKALL int res = mlockall(MCL_CURRENT | MCL_FUTURE); if (res != 0) { fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n", strerror(errno)); } #else fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n"); #endif } /* initialize main thread libevent instance */ #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101 /* If libevent version is larger/equal to 2.0.2-alpha, use newer version */ struct event_config *ev_config; ev_config = event_config_new(); event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK); main_base = event_base_new_with_config(ev_config); event_config_free(ev_config); #else /* Otherwise, use older API */ main_base = event_init(); #endif /* Load initial auth file if required */ if (settings.auth_file) { if (settings.udpport) { fprintf(stderr, "Cannot use UDP with ascii authentication enabled (-U 0 to disable)\n"); exit(EX_USAGE); } switch (authfile_load(settings.auth_file)) { case AUTHFILE_MISSING: // fall through. case AUTHFILE_OPENFAIL: vperror("Could not open authfile [%s] for reading", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OOM: fprintf(stderr, "Out of memory reading password file: %s", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_MALFORMED: fprintf(stderr, "Authfile [%s] has a malformed entry. Should be 'user:password'", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OK: break; } } /* initialize other stuff */ logger_init(); stats_init(); assoc_init(settings.hashpower_init); conn_init(); slabs_init(settings.maxbytes, settings.factor, preallocate, use_slab_sizes ? slab_sizes : NULL); #ifdef EXTSTORE if (storage_file) { enum extstore_res eres; if (settings.ext_compact_under == 0) { settings.ext_compact_under = storage_file->page_count / 4; /* Only rescues non-COLD items if below this threshold */ settings.ext_drop_under = storage_file->page_count / 4; } crc32c_init(); /* Init free chunks to zero. */ for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) { settings.ext_free_memchunks[x] = 0; } storage = extstore_init(storage_file, &ext_cf, &eres); if (storage == NULL) { fprintf(stderr, "Failed to initialize external storage: %s\n", extstore_err(eres)); if (eres == EXTSTORE_INIT_OPEN_FAIL) { perror("extstore open"); } exit(EXIT_FAILURE); } ext_storage = storage; /* page mover algorithm for extstore needs memory prefilled */ slabs_prefill_global(); } #endif if (settings.drop_privileges) { setup_privilege_violations_handler(); } /* * ignore SIGPIPE signals; we can use errno == EPIPE if we * need that information */ if (sigignore(SIGPIPE) == -1) { perror("failed to ignore SIGPIPE; sigaction"); exit(EX_OSERR); } /* start up worker threads if MT mode */ #ifdef EXTSTORE slabs_set_storage(storage); memcached_thread_init(settings.num_threads, storage); init_lru_crawler(storage); #else memcached_thread_init(settings.num_threads, NULL); init_lru_crawler(NULL); #endif if (start_assoc_maint && start_assoc_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (start_lru_crawler && start_item_crawler_thread() != 0) { fprintf(stderr, "Failed to enable LRU crawler thread\n"); exit(EXIT_FAILURE); } #ifdef EXTSTORE if (storage && start_storage_compact_thread(storage) != 0) { fprintf(stderr, "Failed to start storage compaction thread\n"); exit(EXIT_FAILURE); } if (storage && start_storage_write_thread(storage) != 0) { fprintf(stderr, "Failed to start storage writer thread\n"); exit(EXIT_FAILURE); } if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) { #else if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) { #endif fprintf(stderr, "Failed to enable LRU maintainer thread\n"); return 1; } if (settings.slab_reassign && start_slab_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (settings.idle_timeout && start_conn_timeout_thread() == -1) { exit(EXIT_FAILURE); } /* initialise clock event */ clock_handler(0, 0, 0); /* create unix mode sockets after dropping privileges */ if (settings.socketpath != NULL) { errno = 0; if (server_socket_unix(settings.socketpath,settings.access)) { vperror("failed to listen on UNIX socket: %s", settings.socketpath); exit(EX_OSERR); } } /* create the listening socket, bind it, and init */ if (settings.socketpath == NULL) { const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME"); char *temp_portnumber_filename = NULL; size_t len; FILE *portnumber_file = NULL; if (portnumber_filename != NULL) { len = strlen(portnumber_filename)+4+1; temp_portnumber_filename = malloc(len); snprintf(temp_portnumber_filename, len, "%s.lck", portnumber_filename); portnumber_file = fopen(temp_portnumber_filename, "a"); if (portnumber_file == NULL) { fprintf(stderr, "Failed to open \"%s\": %s\n", temp_portnumber_filename, strerror(errno)); } } errno = 0; if (settings.port && server_sockets(settings.port, tcp_transport, portnumber_file)) { vperror("failed to listen on TCP port %d", settings.port); exit(EX_OSERR); } /* * initialization order: first create the listening sockets * (may need root on low ports), then drop root if needed, * then daemonize if needed, then init libevent (in some cases * descriptors created by libevent wouldn't survive forking). */ /* create the UDP listening socket and bind it */ errno = 0; if (settings.udpport && server_sockets(settings.udpport, udp_transport, portnumber_file)) { vperror("failed to listen on UDP port %d", settings.udpport); exit(EX_OSERR); } if (portnumber_file) { fclose(portnumber_file); rename(temp_portnumber_filename, portnumber_filename); } if (temp_portnumber_filename) free(temp_portnumber_filename); } /* Give the sockets a moment to open. I know this is dumb, but the error * is only an advisory. */ usleep(1000); if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n"); exit(EXIT_FAILURE); } if (pid_file != NULL) { save_pid(pid_file); } /* Drop privileges no longer needed */ if (settings.drop_privileges) { drop_privileges(); } /* Initialize the uriencode lookup table. */ uriencode_init(); /* enter the event loop */ if (event_base_loop(main_base, 0) != 0) { retval = EXIT_FAILURE; } stop_assoc_maintenance_thread(); /* remove the PID file if we're a daemon */ if (do_daemonize) remove_pidfile(pid_file); /* Clean up strdup() call for bind() address */ if (settings.inter) free(settings.inter); /* cleanup base */ event_base_free(main_base); return retval; }
static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, sizeof(addr_text) - 1); addr_text[sizeof(addr_text)-1] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } }
static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; size_t pathlen = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: // this strncpy call originally could piss off an address // sanitizer; we supplied the size of the dest buf as a limiter, // but optimized versions of strncpy could read past the end of // *src while looking for a null terminator. Since buf and // sun_path here are both on the stack they could even overlap, // which is "undefined". In all OSS versions of strncpy I could // find this has no effect; it'll still only copy until the first null // terminator is found. Thus it's possible to get the OS to // examine past the end of sun_path but it's unclear to me if this // can cause any actual problem. // // We need a safe_strncpy util function but I'll punt on figuring // that out for now. pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path); if (MAXPATHLEN <= pathlen) { pathlen = MAXPATHLEN - 1; } strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, pathlen); addr_text[pathlen] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } }
{'added': [(3466, ' size_t pathlen = 0;'), (3492, ' // this strncpy call originally could piss off an address'), (3493, ' // sanitizer; we supplied the size of the dest buf as a limiter,'), (3494, ' // but optimized versions of strncpy could read past the end of'), (3495, ' // *src while looking for a null terminator. Since buf and'), (3496, ' // sun_path here are both on the stack they could even overlap,'), (3497, ' // which is "undefined". In all OSS versions of strncpy I could'), (3498, " // find this has no effect; it'll still only copy until the first null"), (3499, " // terminator is found. Thus it's possible to get the OS to"), (3500, " // examine past the end of sun_path but it's unclear to me if this"), (3501, ' // can cause any actual problem.'), (3502, ' //'), (3503, " // We need a safe_strncpy util function but I'll punt on figuring"), (3504, ' // that out for now.'), (3505, ' pathlen = sizeof(((struct sockaddr_un *)sock_addr)->sun_path);'), (3506, ' if (MAXPATHLEN <= pathlen) {'), (3507, ' pathlen = MAXPATHLEN - 1;'), (3508, ' }'), (3511, ' pathlen);'), (3512, " addr_text[pathlen] = '\\0';")], 'deleted': [(3493, ' sizeof(addr_text) - 1);'), (3494, " addr_text[sizeof(addr_text)-1] = '\\0';")]}
20
2
6,694
43,967
https://github.com/memcached/memcached
CVE-2019-15026
['CWE-125']
mpeg4videodec.c
ff_mpeg4_decode_picture_header
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); // for Simple profile, level 0 if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); // for Simple profile, level 0 if (*profile == 0 && *level == 8) { *level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); }
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); }
{'added': [(1983, 'static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)'), (1986, ' *profile = get_bits(gb, 4);'), (1987, ' *level = get_bits(gb, 4);'), (1990, ' if (*profile == 0 && *level == 8) {'), (1991, ' *level = 0;'), (3214, ' int profile, level;'), (3215, ' mpeg4_decode_profile_level(s, gb, &profile, &level);'), (3216, ' if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&'), (3217, ' (level > 0 && level < 9)) {'), (3221, ' } else if (s->studio_profile) {'), (3222, ' avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\\n");'), (3223, ' return AVERROR_PATCHWELCOME;'), (3225, ' s->avctx->profile = profile;'), (3226, ' s->avctx->level = level;'), (3247, ' av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);')], 'deleted': [(1983, 'static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)'), (1986, ' s->avctx->profile = get_bits(gb, 4);'), (1987, ' s->avctx->level = get_bits(gb, 4);'), (1990, ' if (s->avctx->profile == 0 && s->avctx->level == 8) {'), (1991, ' s->avctx->level = 0;'), (3214, ' mpeg4_decode_profile_level(s, gb);'), (3215, ' if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&'), (3216, ' (s->avctx->level > 0 && s->avctx->level < 9)) {')]}
15
8
2,816
24,174
https://github.com/FFmpeg/FFmpeg
CVE-2018-13301
['CWE-476']
mpeg4videodec.c
mpeg4_decode_profile_level
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); // for Simple profile, level 0 if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); // for Simple profile, level 0 if (*profile == 0 && *level == 8) { *level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { int profile, level; mpeg4_decode_profile_level(s, gb, &profile, &level); if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (level > 0 && level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } else if (s->studio_profile) { avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n"); return AVERROR_PATCHWELCOME; } s->avctx->profile = profile; s->avctx->level = level; } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO); if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); // for Simple profile, level 0 if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; }
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); // for Simple profile, level 0 if (*profile == 0 && *level == 8) { *level = 0; } return 0; }
{'added': [(1983, 'static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)'), (1986, ' *profile = get_bits(gb, 4);'), (1987, ' *level = get_bits(gb, 4);'), (1990, ' if (*profile == 0 && *level == 8) {'), (1991, ' *level = 0;'), (3214, ' int profile, level;'), (3215, ' mpeg4_decode_profile_level(s, gb, &profile, &level);'), (3216, ' if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&'), (3217, ' (level > 0 && level < 9)) {'), (3221, ' } else if (s->studio_profile) {'), (3222, ' avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\\n");'), (3223, ' return AVERROR_PATCHWELCOME;'), (3225, ' s->avctx->profile = profile;'), (3226, ' s->avctx->level = level;'), (3247, ' av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);')], 'deleted': [(1983, 'static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)'), (1986, ' s->avctx->profile = get_bits(gb, 4);'), (1987, ' s->avctx->level = get_bits(gb, 4);'), (1990, ' if (s->avctx->profile == 0 && s->avctx->level == 8) {'), (1991, ' s->avctx->level = 0;'), (3214, ' mpeg4_decode_profile_level(s, gb);'), (3215, ' if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&'), (3216, ' (s->avctx->level > 0 && s->avctx->level < 9)) {')]}
15
8
2,816
24,174
https://github.com/FFmpeg/FFmpeg
CVE-2018-13301
['CWE-476']
regparse.c
fetch_token
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; }
fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; }
{'added': [(3023, ' if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;'), (3395, ' if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;')], 'deleted': [(3023, ' if (num < 0) return ONIGERR_TOO_BIG_NUMBER;'), (3395, ' if (num < 0) return ONIGERR_TOO_BIG_NUMBER;')]}
2
2
4,485
26,541
https://github.com/kkos/oniguruma
CVE-2017-9226
['CWE-787']
regparse.c
fetch_token_in_cc
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; }
fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; }
{'added': [(3023, ' if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;'), (3395, ' if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER;')], 'deleted': [(3023, ' if (num < 0) return ONIGERR_TOO_BIG_NUMBER;'), (3395, ' if (num < 0) return ONIGERR_TOO_BIG_NUMBER;')]}
2
2
4,485
26,541
https://github.com/kkos/oniguruma
CVE-2017-9226
['CWE-787']
imginfo.c
main
/* * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Image Information Program * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <assert.h> #include <stdint.h> #include <jasper/jasper.h> /******************************************************************************\ * \******************************************************************************/ typedef enum { OPT_HELP, OPT_VERSION, OPT_VERBOSE, OPT_INFILE, OPT_DEBUG, OPT_MAXMEM } optid_t; /******************************************************************************\ * \******************************************************************************/ static void usage(void); static void cmdinfo(void); /******************************************************************************\ * \******************************************************************************/ static jas_opt_t opts[] = { {OPT_HELP, "help", 0}, {OPT_VERSION, "version", 0}, {OPT_VERBOSE, "verbose", 0}, {OPT_INFILE, "f", JAS_OPT_HASARG}, {OPT_DEBUG, "debug-level", JAS_OPT_HASARG}, #if defined(JAS_DEFAULT_MAX_MEM_USAGE) {OPT_MAXMEM, "memory-limit", JAS_OPT_HASARG}, #endif {-1, 0, 0} }; static char *cmdname = 0; /******************************************************************************\ * Main program. \******************************************************************************/ int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; } /******************************************************************************\ * \******************************************************************************/ static void cmdinfo() { fprintf(stderr, "Image Information Utility (Version %s).\n", JAS_VERSION); fprintf(stderr, "Copyright (c) 2001 Michael David Adams.\n" "All rights reserved.\n" ); } static void usage() { cmdinfo(); fprintf(stderr, "usage:\n"); fprintf(stderr,"%s ", cmdname); fprintf(stderr, "[-f image_file]\n"); exit(EXIT_FAILURE); }
/* * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Image Information Program * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <assert.h> #include <stdint.h> #include <jasper/jasper.h> /******************************************************************************\ * \******************************************************************************/ typedef enum { OPT_HELP, OPT_VERSION, OPT_VERBOSE, OPT_INFILE, OPT_DEBUG, OPT_MAXSAMPLES, OPT_MAXMEM } optid_t; /******************************************************************************\ * \******************************************************************************/ static void usage(void); static void cmdinfo(void); /******************************************************************************\ * \******************************************************************************/ static jas_opt_t opts[] = { {OPT_HELP, "help", 0}, {OPT_VERSION, "version", 0}, {OPT_VERBOSE, "verbose", 0}, {OPT_INFILE, "f", JAS_OPT_HASARG}, {OPT_DEBUG, "debug-level", JAS_OPT_HASARG}, {OPT_MAXSAMPLES, "max-samples", JAS_OPT_HASARG}, #if defined(JAS_DEFAULT_MAX_MEM_USAGE) {OPT_MAXMEM, "memory-limit", JAS_OPT_HASARG}, #endif {-1, 0, 0} }; static char *cmdname = 0; /******************************************************************************\ * Main program. \******************************************************************************/ int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; size_t max_samples; char optstr[32]; if (jas_init()) { abort(); } cmdname = argv[0]; max_samples = 64 * JAS_MEBI; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXSAMPLES: max_samples = strtoull(jas_optarg, 0, 10); break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } snprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples); /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, optstr))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(fmtname = jas_image_fmttostr(fmtid))) { jas_eprintf("format name lookup failed\n"); return EXIT_FAILURE; } if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, JAS_CAST(long, jas_image_rawsize(image))); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; } /******************************************************************************\ * \******************************************************************************/ static void cmdinfo() { fprintf(stderr, "Image Information Utility (Version %s).\n", JAS_VERSION); fprintf(stderr, "Copyright (c) 2001 Michael David Adams.\n" "All rights reserved.\n" ); } static void usage() { cmdinfo(); fprintf(stderr, "usage:\n"); fprintf(stderr,"%s ", cmdname); fprintf(stderr, "[-f image_file]\n"); exit(EXIT_FAILURE); }
int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; size_t max_samples; char optstr[32]; if (jas_init()) { abort(); } cmdname = argv[0]; max_samples = 64 * JAS_MEBI; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXSAMPLES: max_samples = strtoull(jas_optarg, 0, 10); break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { fprintf(stderr, "cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { fprintf(stderr, "cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, "unknown image format\n"); } snprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples); /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, optstr))) { jas_stream_close(instream); fprintf(stderr, "cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(fmtname = jas_image_fmttostr(fmtid))) { jas_eprintf("format name lookup failed\n"); return EXIT_FAILURE; } if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, "warning: image has no components\n"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, JAS_CAST(long, jas_image_rawsize(image))); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }
{'added': [(91, '\tOPT_MAXSAMPLES,'), (112, '\t{OPT_MAXSAMPLES, "max-samples", JAS_OPT_HASARG},'), (140, '\tsize_t max_samples;'), (141, '\tchar optstr[32];'), (149, '\tmax_samples = 64 * JAS_MEBI;'), (173, '\t\tcase OPT_MAXSAMPLES:'), (174, '\t\t\tmax_samples = strtoull(jas_optarg, 0, 10);'), (175, '\t\t\tbreak;'), (210, '\tsnprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples);'), (211, ''), (213, '\tif (!(image = jas_image_decode(instream, fmtid, optstr))) {'), (222, '\tif (!(fmtname = jas_image_fmttostr(fmtid))) {'), (223, '\t\tjas_eprintf("format name lookup failed\\n");'), (224, '\t\treturn EXIT_FAILURE;'), (225, '\t}'), (226, ''), (239, '\tprintf("%s %d %d %d %d %ld\\n", fmtname, numcmpts, width, height, depth,'), (240, '\t JAS_CAST(long, jas_image_rawsize(image)));')], 'deleted': [(203, '\tif (!(image = jas_image_decode(instream, fmtid, 0))) {'), (224, '\tif (!(fmtname = jas_image_fmttostr(fmtid))) {'), (225, '\t\tabort();'), (226, '\t}'), (227, '\tprintf("%s %d %d %d %d %ld\\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));')]}
18
5
144
689
https://github.com/mdadams/jasper
CVE-2016-9395
['CWE-20']
jpeg2000dec.c
jpeg2000_decode_tile
/* * JPEG 2000 image decoder * Copyright (c) 2007 Kamil Nowosad * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * JPEG 2000 image decoder */ #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "thread.h" #include "jpeg2000.h" #define JP2_SIG_TYPE 0x6A502020 #define JP2_SIG_VALUE 0x0D0A870A #define JP2_CODESTREAM 0x6A703263 #define JP2_HEADER 0x6A703268 #define HAD_COC 0x01 #define HAD_QCC 0x02 typedef struct Jpeg2000TilePart { uint8_t tile_index; // Tile index who refers the tile-part const uint8_t *tp_end; GetByteContext tpg; // bit stream in tile-part } Jpeg2000TilePart; /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile * one per component, so tile_part elements have a size of 3 */ typedef struct Jpeg2000Tile { Jpeg2000Component *comp; uint8_t properties[4]; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; Jpeg2000TilePart tile_part[4]; uint16_t tp_idx; // Tile-part index } Jpeg2000Tile; typedef struct Jpeg2000DecoderContext { AVClass *class; AVCodecContext *avctx; GetByteContext g; int width, height; int image_offset_x, image_offset_y; int tile_offset_x, tile_offset_y; uint8_t cbps[4]; // bits per sample in particular components uint8_t sgnd[4]; // if a component is signed uint8_t properties[4]; int cdx[4], cdy[4]; int precision; int ncomponents; int colour_space; uint32_t palette[256]; int8_t pal8; int cdef[4]; int tile_width, tile_height; unsigned numXtiles, numYtiles; int maxtilelen; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; int bit_index; int curtileno; Jpeg2000Tile *tile; /*options parameters*/ int reduction_factor; } Jpeg2000DecoderContext; /* get_bits functions for JPEG2000 packet bitstream * It is a get_bit function with a bit-stuffing routine. If the value of the * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB. * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */ static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu); } s->bit_index--; res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1; } return res; } static void jpeg2000_flush(Jpeg2000DecoderContext *s) { if (bytestream2_get_byte(&s->g) == 0xff) bytestream2_skip(&s->g, 1); s->bit_index = 8; } /* decode the value stored in node */ static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node, int threshold) { Jpeg2000TgtNode *stack[30]; int sp = -1, curval = 0; if (!node) return AVERROR_INVALIDDATA; while (node && !node->vis) { stack[++sp] = node; node = node->parent; } if (node) curval = node->val; else curval = stack[sp]->val; while (curval < threshold && sp >= 0) { if (curval < stack[sp]->val) curval = stack[sp]->val; while (curval < threshold) { int ret; if ((ret = get_bits(s, 1)) > 0) { stack[sp]->vis++; break; } else if (!ret) curval++; else return ret; } stack[sp]->val = curval; sp--; } return curval; } static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components, int bpc, uint32_t log2_chroma_wh, int pal8) { int match = 1; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc->nb_components != components) { return 0; } switch (components) { case 4: match = match && desc->comp[3].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 14 & 3) == 0 && (log2_chroma_wh >> 12 & 3) == 0; case 3: match = match && desc->comp[2].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h; case 2: match = match && desc->comp[1].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h; case 1: match = match && desc->comp[0].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 2 & 3) == 0 && (log2_chroma_wh & 3) == 0 && (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL; } return match; } // pix_fmts with lower bpp have to be listed before // similar pix_fmts with higher bpp. #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \ AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \ AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \ AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \ AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \ AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \ AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \ AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \ AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \ AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \ AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS}; static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS}; static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS}; static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS}; static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS}; /* marker segments */ /* get sizes and offsets of image, tiles; number of components */ static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } /* get common part for COD and COC segments */ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } /* get coding parameters for a particular tile or whole image*/ static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { Jpeg2000CodingStyle tmp; int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; tmp.csty = bytestream2_get_byteu(&s->g); // get progression order tmp.prog_order = bytestream2_get_byteu(&s->g); tmp.nlayers = bytestream2_get_be16u(&s->g); tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation if (tmp.mct && s->ncomponents < 3) { av_log(s->avctx, AV_LOG_ERROR, "MCT %d with too few components (%d)\n", tmp.mct, s->ncomponents); return AVERROR_INVALIDDATA; } if ((ret = get_cox(s, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_COC)) memcpy(c + compno, &tmp, sizeof(tmp)); return 0; } /* Get coding parameters for a component in the whole image or a * particular tile. */ static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; return 0; } /* Get common part for QCD and QCC segments. */ static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q) { int i, x; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; x = bytestream2_get_byteu(&s->g); // Sqcd q->nguardbits = x >> 5; q->quantsty = x & 0x1f; if (q->quantsty == JPEG2000_QSTY_NONE) { n -= 3; if (bytestream2_get_bytes_left(&s->g) < n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) q->expn[i] = bytestream2_get_byteu(&s->g) >> 3; } else if (q->quantsty == JPEG2000_QSTY_SI) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; x = bytestream2_get_be16u(&s->g); q->expn[0] = x >> 11; q->mant[0] = x & 0x7ff; for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) { int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3); q->expn[i] = curexpn; q->mant[i] = q->mant[0]; } } else { n = (n - 3) >> 1; if (bytestream2_get_bytes_left(&s->g) < 2 * n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) { x = bytestream2_get_be16u(&s->g); q->expn[i] = x >> 11; q->mant[i] = x & 0x7ff; } } return 0; } /* Get quantization parameters for a particular tile or a whole image. */ static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { Jpeg2000QuantStyle tmp; int compno, ret; if ((ret = get_qcx(s, n, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_QCC)) memcpy(q + compno, &tmp, sizeof(tmp)); return 0; } /* Get quantization parameters for a component in the whole image * on in a particular tile. */ static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); } /* Get start of tile segment. */ static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %d components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; } /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1 * Used to know the number of tile parts and lengths. * There may be multiple TLMs in the header. * TODO: The function is not used for tile-parts management, nor anywhere else. * It can be useful to allocate memory for tile parts, before managing the SOT * markers. Parsing the TLM header is needed to increment the input header * buffer. * This marker is mandatory for DCI. */ static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n) { uint8_t Stlm, ST, SP, tile_tlm, i; bytestream2_get_byte(&s->g); /* Ztlm: skipped */ Stlm = bytestream2_get_byte(&s->g); // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); ST = (Stlm >> 4) & 0x03; // TODO: Manage case of ST = 0b11 --> raise error SP = (Stlm >> 6) & 0x01; tile_tlm = (n - 4) / ((SP + 1) * 2 + ST); for (i = 0; i < tile_tlm; i++) { switch (ST) { case 0: break; case 1: bytestream2_get_byte(&s->g); break; case 2: bytestream2_get_be16(&s->g); break; case 3: bytestream2_get_be32(&s->g); break; } if (SP == 0) { bytestream2_get_be16(&s->g); } else { bytestream2_get_be32(&s->g); } } return 0; } static int init_tile(Jpeg2000DecoderContext *s, int tileno) { int compno; int tilex = tileno % s->numXtiles; int tiley = tileno / s->numXtiles; Jpeg2000Tile *tile = s->tile + tileno; if (!tile->comp) return AVERROR(ENOMEM); for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; int ret; // global bandno comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x); comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width); comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y); comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height); comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor); comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor); comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor); comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor); if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx)) return ret; } return 0; } /* Read the number of coding passes. */ static int getnpasses(Jpeg2000DecoderContext *s) { int num; if (!get_bits(s, 1)) return 1; if (!get_bits(s, 1)) return 2; if ((num = get_bits(s, 2)) != 3) return num < 0 ? num : 3 + num; if ((num = get_bits(s, 5)) != 31) return num < 0 ? num : 6 + num; num = get_bits(s, 7); return num < 0 ? num : 37 + num; } static int getlblockinc(Jpeg2000DecoderContext *s) { int res = 0, ret; while (ret = get_bits(s, 1)) { if (ret < 0) return ret; res++; } return res; } static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %zu", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc = ret; cblk->npasses += newpasses; } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2 ) { av_log(s->avctx, AV_LOG_ERROR, "Block length %d or lengthinc %d is too large\n", cblk->length, cblk->lengthinc); return AVERROR_INVALIDDATA; } bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } return 0; } static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int ret = 0; int layno, reslevelno, compno, precno, ok_reslevel; int x, y; s->bit_index = 8; switch (tile->codsty[0].prog_order) { case JPEG2000_PGOD_RLCP: avpriv_request_sample(s->avctx, "Progression order RLCP"); case JPEG2000_PGOD_LRCP: for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { ok_reslevel = 1; for (reslevelno = 0; ok_reslevel; reslevelno++) { ok_reslevel = 0; for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; if (reslevelno < codsty->nreslevels) { Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; ok_reslevel = 1; for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } break; case JPEG2000_PGOD_CPRL: for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; /* Set bit stream buffer address according to tile-part. * For DCinema one tile-part per component, so can be * indexed by component. */ s->g = tile->tile_part[compno].tpg; /* Position loop (y axis) * TODO: Automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (y = 0; y < s->height; y += 256) { /* Position loop (y axis) * TODO: automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (x = 0; x < s->width; x += 256) { for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { uint16_t prcx, prcy; uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) || (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) || (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; // check if a precinct exists prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width; prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height; precno = prcx + rlevel->num_precincts_x * prcy; for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } } break; case JPEG2000_PGOD_RPCL: avpriv_request_sample(s->avctx, "Progression order RPCL"); ret = AVERROR_PATCHWELCOME; break; case JPEG2000_PGOD_PCRL: avpriv_request_sample(s->avctx, "Progression order PCRL"); ret = AVERROR_PATCHWELCOME; break; default: break; } /* EOC marker reached */ bytestream2_skip(&s->g, 2); return ret; } /* TIER-1 routines */ static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) { if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB) && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) { int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit); if (bpass_csty_symbol) t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask; else t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS; } } } static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno) { int phalf, nhalf; int y0, x, y; phalf = 1 << (bpno - 1); nhalf = -phalf; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) { int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]); int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf; t1->data[y][x] += t1->data[y][x] < 0 ? -r : r; t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF; } } static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y, runlen, dec; for (y0 = 0; y0 < height; y0 += 4) { for (x = 0; x < width; x++) { if (y0 + 3 < height && !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) { if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL)) continue; runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); dec = 1; } else { runlen = 0; dec = 0; } for (y = y0 + runlen; y < y0 + 4 && y < height; y++) { if (!dec) { if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno)); } } if (dec) { int xorbit; int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1], &xorbit); t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } dec = 0; t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS; } } } if (seg_symbols) { int val; val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); if (val != 0xa) av_log(s->avctx, AV_LOG_ERROR, "Segmentation symbol value incorrect\n"); } } static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; av_assert0(width <= JPEG2000_MAX_CBLKW); av_assert0(height <= JPEG2000_MAX_CBLKH); for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } /* TODO: Verify dequantization for lossless case * comp->data can be float or int * band->stepsize can be float or int * depending on the type of DWT transformation. * see ISO/IEC 15444-1:2002 A.6.1 */ /* Float dequantization of a codeblock.*/ static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = src[i] * band->f_stepsize; } } /* Integer dequantization of a codeblock.*/ static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15; } } /* Inverse ICT parameters in float and integer. * int value = (float value) * (1<<16) */ static const float f_ict_params[4] = { 1.402f, 0.34413f, 0.71414f, 1.772f }; static const int i_ict_params[4] = { 91881, 22553, 46802, 116130 }; static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int i, csize = 1; int32_t *src[3], i0, i1, i2; float *srcf[3], i0f, i1f, i2f; for (i = 1; i < 3; i++) if (tile->codsty[0].transform != tile->codsty[i].transform) { av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n"); return; } for (i = 0; i < 3; i++) if (tile->codsty[0].transform == FF_DWT97) srcf[i] = tile->comp[i].f_data; else src [i] = tile->comp[i].i_data; for (i = 0; i < 2; i++) csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0]; switch (tile->codsty[0].transform) { case FF_DWT97: for (i = 0; i < csize; i++) { i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]); i1f = *srcf[0] - (f_ict_params[1] * *srcf[1]) - (f_ict_params[2] * *srcf[2]); i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]); *srcf[0]++ = i0f; *srcf[1]++ = i1f; *srcf[2]++ = i2f; } break; case FF_DWT97_INT: for (i = 0; i < csize; i++) { i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16); i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16) - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16); i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16); *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; case FF_DWT53: for (i = 0; i < csize; i++) { i1 = *src[0] - (*src[2] + *src[1] >> 2); i0 = i1 + *src[2]; i2 = i1 + *src[1]; *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; } } static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s) { int tileno, compno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { if (s->tile[tileno].comp) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = s->tile[tileno].comp + compno; Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno; ff_jpeg2000_cleanup(comp, codsty); } av_freep(&s->tile[tileno].comp); } } av_freep(&s->tile); memset(s->codsty, 0, sizeof(s->codsty)); memset(s->qntsty, 0, sizeof(s->qntsty)); s->numXtiles = s->numYtiles = 0; } static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s) { Jpeg2000CodingStyle *codsty = s->codsty; Jpeg2000QuantStyle *qntsty = s->qntsty; uint8_t *properties = s->properties; for (;;) { int len, ret = 0; uint16_t marker; int oldpos; if (bytestream2_get_bytes_left(&s->g) < 2) { av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n"); break; } marker = bytestream2_get_be16u(&s->g); oldpos = bytestream2_tell(&s->g); if (marker == JPEG2000_SOD) { Jpeg2000Tile *tile; Jpeg2000TilePart *tp; if (!s->tile) { av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n"); return AVERROR_INVALIDDATA; } if (s->curtileno < 0) { av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n"); return AVERROR_INVALIDDATA; } tile = s->tile + s->curtileno; tp = tile->tile_part + tile->tp_idx; if (tp->tp_end < s->g.buffer) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n"); return AVERROR_INVALIDDATA; } bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer); bytestream2_skip(&s->g, tp->tp_end - s->g.buffer); continue; } if (marker == JPEG2000_EOC) break; len = bytestream2_get_be16(&s->g); if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) return AVERROR_INVALIDDATA; switch (marker) { case JPEG2000_SIZ: ret = get_siz(s); if (!s->tile) s->numXtiles = s->numYtiles = 0; break; case JPEG2000_COC: ret = get_coc(s, codsty, properties); break; case JPEG2000_COD: ret = get_cod(s, codsty, properties); break; case JPEG2000_QCC: ret = get_qcc(s, len, qntsty, properties); break; case JPEG2000_QCD: ret = get_qcd(s, len, qntsty, properties); break; case JPEG2000_SOT: if (!(ret = get_sot(s, len))) { av_assert1(s->curtileno >= 0); codsty = s->tile[s->curtileno].codsty; qntsty = s->tile[s->curtileno].qntsty; properties = s->tile[s->curtileno].properties; } break; case JPEG2000_COM: // the comment is ignored bytestream2_skip(&s->g, len - 2); break; case JPEG2000_TLM: // Tile-part lengths ret = get_tlm(s, len); break; default: av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%X\n", marker, bytestream2_tell(&s->g) - 4); bytestream2_skip(&s->g, len - 2); break; } if (bytestream2_tell(&s->g) - oldpos != len || ret) { av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker); return ret ? ret : -1; } } return 0; } /* Read bit stream packets --> T2 operation. */ static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s) { int ret = 0; int tileno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { Jpeg2000Tile *tile = s->tile + tileno; if (ret = init_tile(s, tileno)) return ret; s->g = tile->tile_part[0].tpg; if (ret = jpeg2000_decode_packets(s, tile)) return ret; } return 0; } static int jp2_find_codestream(Jpeg2000DecoderContext *s) { uint32_t atom_size, atom, atom_end; int search_range = 10; while (search_range && bytestream2_get_bytes_left(&s->g) >= 8) { atom_size = bytestream2_get_be32u(&s->g); atom = bytestream2_get_be32u(&s->g); atom_end = bytestream2_tell(&s->g) + atom_size - 8; if (atom == JP2_CODESTREAM) return 1; if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size) return 0; if (atom == JP2_HEADER && atom_size >= 16) { uint32_t atom2_size, atom2, atom2_end; do { atom2_size = bytestream2_get_be32u(&s->g); atom2 = bytestream2_get_be32u(&s->g); atom2_end = bytestream2_tell(&s->g) + atom2_size - 8; if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size) break; if (atom2 == JP2_CODESTREAM) { return 1; } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) { int method = bytestream2_get_byteu(&s->g); bytestream2_skipu(&s->g, 2); if (method == 1) { s->colour_space = bytestream2_get_be32u(&s->g); } } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) { int i, size, colour_count, colour_channels, colour_depth[3]; uint32_t r, g, b; colour_count = bytestream2_get_be16u(&s->g); colour_channels = bytestream2_get_byteu(&s->g); // FIXME: Do not ignore channel_sign colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; size = (colour_depth[0] + 7 >> 3) * colour_count + (colour_depth[1] + 7 >> 3) * colour_count + (colour_depth[2] + 7 >> 3) * colour_count; if (colour_count > 256 || colour_channels != 3 || colour_depth[0] > 16 || colour_depth[1] > 16 || colour_depth[2] > 16 || atom2_size < size) { avpriv_request_sample(s->avctx, "Unknown palette"); bytestream2_seek(&s->g, atom2_end, SEEK_SET); continue; } s->pal8 = 1; for (i = 0; i < colour_count; i++) { if (colour_depth[0] <= 8) { r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0]; r |= r >> colour_depth[0]; } else { r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8; } if (colour_depth[1] <= 8) { g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1]; r |= r >> colour_depth[1]; } else { g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8; } if (colour_depth[2] <= 8) { b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2]; r |= r >> colour_depth[2]; } else { b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8; } s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b; } } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) { int n = bytestream2_get_be16u(&s->g); for (; n>0; n--) { int cn = bytestream2_get_be16(&s->g); int av_unused typ = bytestream2_get_be16(&s->g); int asoc = bytestream2_get_be16(&s->g); if (cn < 4 || asoc < 4) s->cdef[cn] = asoc; } } bytestream2_seek(&s->g, atom2_end, SEEK_SET); } while (atom_end - atom2_end >= 8); } else { search_range--; } bytestream2_seek(&s->g, atom_end, SEEK_SET); } return 0; } static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; bytestream2_init(&s->g, avpkt->data, avpkt->size); s->curtileno = -1; memset(s->cdef, -1, sizeof(s->cdef)); if (bytestream2_get_bytes_left(&s->g) < 2) { ret = AVERROR_INVALIDDATA; goto end; } // check if the image is in jp2 format if (bytestream2_get_bytes_left(&s->g) >= 12 && (bytestream2_get_be32u(&s->g) == 12) && (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) && (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); ret = AVERROR_INVALIDDATA; goto end; } } else { bytestream2_seek(&s->g, 0, SEEK_SET); } while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC) bytestream2_skip(&s->g, 1); if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); ret = AVERROR_INVALIDDATA; goto end; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) goto end; picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; jpeg2000_dec_cleanup(s); *got_frame = 1; if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t)); return bytestream2_tell(&s->g); end: jpeg2000_dec_cleanup(s); return ret; } static void jpeg2000_init_static_data(AVCodec *codec) { ff_jpeg2000_init_tier1_luts(); ff_mqc_init_context_tables(); } #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "lowres", "Lower the decoding resolution by a power of two", OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD }, { NULL }, }; static const AVProfile profiles[] = { { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" }, { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" }, { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" }, { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" }, { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" }, { FF_PROFILE_UNKNOWN }, }; static const AVClass jpeg2000_class = { .class_name = "jpeg2000", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_jpeg2000_decoder = { .name = "jpeg2000", .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_JPEG2000, .capabilities = CODEC_CAP_FRAME_THREADS, .priv_data_size = sizeof(Jpeg2000DecoderContext), .init_static_data = jpeg2000_init_static_data, .decode = jpeg2000_decode_frame, .priv_class = &jpeg2000_class, .max_lowres = 5, .profiles = NULL_IF_CONFIG_SMALL(profiles) };
/* * JPEG 2000 image decoder * Copyright (c) 2007 Kamil Nowosad * Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * JPEG 2000 image decoder */ #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #include "thread.h" #include "jpeg2000.h" #define JP2_SIG_TYPE 0x6A502020 #define JP2_SIG_VALUE 0x0D0A870A #define JP2_CODESTREAM 0x6A703263 #define JP2_HEADER 0x6A703268 #define HAD_COC 0x01 #define HAD_QCC 0x02 typedef struct Jpeg2000TilePart { uint8_t tile_index; // Tile index who refers the tile-part const uint8_t *tp_end; GetByteContext tpg; // bit stream in tile-part } Jpeg2000TilePart; /* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile * one per component, so tile_part elements have a size of 3 */ typedef struct Jpeg2000Tile { Jpeg2000Component *comp; uint8_t properties[4]; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; Jpeg2000TilePart tile_part[4]; uint16_t tp_idx; // Tile-part index } Jpeg2000Tile; typedef struct Jpeg2000DecoderContext { AVClass *class; AVCodecContext *avctx; GetByteContext g; int width, height; int image_offset_x, image_offset_y; int tile_offset_x, tile_offset_y; uint8_t cbps[4]; // bits per sample in particular components uint8_t sgnd[4]; // if a component is signed uint8_t properties[4]; int cdx[4], cdy[4]; int precision; int ncomponents; int colour_space; uint32_t palette[256]; int8_t pal8; int cdef[4]; int tile_width, tile_height; unsigned numXtiles, numYtiles; int maxtilelen; Jpeg2000CodingStyle codsty[4]; Jpeg2000QuantStyle qntsty[4]; int bit_index; int curtileno; Jpeg2000Tile *tile; /*options parameters*/ int reduction_factor; } Jpeg2000DecoderContext; /* get_bits functions for JPEG2000 packet bitstream * It is a get_bit function with a bit-stuffing routine. If the value of the * byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB. * cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */ static int get_bits(Jpeg2000DecoderContext *s, int n) { int res = 0; while (--n >= 0) { res <<= 1; if (s->bit_index == 0) { s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu); } s->bit_index--; res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1; } return res; } static void jpeg2000_flush(Jpeg2000DecoderContext *s) { if (bytestream2_get_byte(&s->g) == 0xff) bytestream2_skip(&s->g, 1); s->bit_index = 8; } /* decode the value stored in node */ static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node, int threshold) { Jpeg2000TgtNode *stack[30]; int sp = -1, curval = 0; if (!node) return AVERROR_INVALIDDATA; while (node && !node->vis) { stack[++sp] = node; node = node->parent; } if (node) curval = node->val; else curval = stack[sp]->val; while (curval < threshold && sp >= 0) { if (curval < stack[sp]->val) curval = stack[sp]->val; while (curval < threshold) { int ret; if ((ret = get_bits(s, 1)) > 0) { stack[sp]->vis++; break; } else if (!ret) curval++; else return ret; } stack[sp]->val = curval; sp--; } return curval; } static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components, int bpc, uint32_t log2_chroma_wh, int pal8) { int match = 1; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc->nb_components != components) { return 0; } switch (components) { case 4: match = match && desc->comp[3].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 14 & 3) == 0 && (log2_chroma_wh >> 12 & 3) == 0; case 3: match = match && desc->comp[2].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h; case 2: match = match && desc->comp[1].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w && (log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h; case 1: match = match && desc->comp[0].depth_minus1 + 1 >= bpc && (log2_chroma_wh >> 2 & 3) == 0 && (log2_chroma_wh & 3) == 0 && (desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL; } return match; } // pix_fmts with lower bpp have to be listed before // similar pix_fmts with higher bpp. #define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64 #define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16 #define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \ AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \ AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \ AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \ AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \ AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \ AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \ AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \ AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \ AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \ AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16 #define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12 static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS}; static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS}; static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS}; static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS}; static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS, GRAY_PIXEL_FORMATS, YUV_PIXEL_FORMATS, XYZ_PIXEL_FORMATS}; /* marker segments */ /* get sizes and offsets of image, tiles; number of components */ static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } /* get common part for COD and COC segments */ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) { uint8_t byte; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; /* nreslevels = number of resolution levels = number of decomposition level +1 */ c->nreslevels = bytestream2_get_byteu(&s->g) + 1; if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) { av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels); return AVERROR_INVALIDDATA; } /* compute number of resolution levels to decode */ if (c->nreslevels < s->reduction_factor) c->nreslevels2decode = 1; else c->nreslevels2decode = c->nreslevels - s->reduction_factor; c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 || c->log2_cblk_width + c->log2_cblk_height > 12) { av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n"); return AVERROR_INVALIDDATA; } if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { avpriv_request_sample(s->avctx, "cblk size > 64"); return AVERROR_PATCHWELCOME; } c->cblk_style = bytestream2_get_byteu(&s->g); if (c->cblk_style != 0) { // cblk style av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style); } c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type /* set integer 9/7 DWT in case of BITEXACT flag */ if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97)) c->transform = FF_DWT97_INT; if (c->csty & JPEG2000_CSTY_PREC) { int i; for (i = 0; i < c->nreslevels; i++) { byte = bytestream2_get_byte(&s->g); c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy } } else { memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths )); memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights)); } return 0; } /* get coding parameters for a particular tile or whole image*/ static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { Jpeg2000CodingStyle tmp; int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 5) return AVERROR_INVALIDDATA; tmp.csty = bytestream2_get_byteu(&s->g); // get progression order tmp.prog_order = bytestream2_get_byteu(&s->g); tmp.nlayers = bytestream2_get_be16u(&s->g); tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation if (tmp.mct && s->ncomponents < 3) { av_log(s->avctx, AV_LOG_ERROR, "MCT %d with too few components (%d)\n", tmp.mct, s->ncomponents); return AVERROR_INVALIDDATA; } if ((ret = get_cox(s, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_COC)) memcpy(c + compno, &tmp, sizeof(tmp)); return 0; } /* Get coding parameters for a component in the whole image or a * particular tile. */ static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; return 0; } /* Get common part for QCD and QCC segments. */ static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q) { int i, x; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; x = bytestream2_get_byteu(&s->g); // Sqcd q->nguardbits = x >> 5; q->quantsty = x & 0x1f; if (q->quantsty == JPEG2000_QSTY_NONE) { n -= 3; if (bytestream2_get_bytes_left(&s->g) < n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) q->expn[i] = bytestream2_get_byteu(&s->g) >> 3; } else if (q->quantsty == JPEG2000_QSTY_SI) { if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; x = bytestream2_get_be16u(&s->g); q->expn[0] = x >> 11; q->mant[0] = x & 0x7ff; for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) { int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3); q->expn[i] = curexpn; q->mant[i] = q->mant[0]; } } else { n = (n - 3) >> 1; if (bytestream2_get_bytes_left(&s->g) < 2 * n || n > JPEG2000_MAX_DECLEVELS*3) return AVERROR_INVALIDDATA; for (i = 0; i < n; i++) { x = bytestream2_get_be16u(&s->g); q->expn[i] = x >> 11; q->mant[i] = x & 0x7ff; } } return 0; } /* Get quantization parameters for a particular tile or a whole image. */ static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { Jpeg2000QuantStyle tmp; int compno, ret; if ((ret = get_qcx(s, n, &tmp)) < 0) return ret; for (compno = 0; compno < s->ncomponents; compno++) if (!(properties[compno] & HAD_QCC)) memcpy(q + compno, &tmp, sizeof(tmp)); return 0; } /* Get quantization parameters for a component in the whole image * on in a particular tile. */ static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (bytestream2_get_bytes_left(&s->g) < 1) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); } /* Get start of tile segment. */ static int get_sot(Jpeg2000DecoderContext *s, int n) { Jpeg2000TilePart *tp; uint16_t Isot; uint32_t Psot; uint8_t TPsot; if (bytestream2_get_bytes_left(&s->g) < 8) return AVERROR_INVALIDDATA; s->curtileno = 0; Isot = bytestream2_get_be16u(&s->g); // Isot if (Isot >= s->numXtiles * s->numYtiles) return AVERROR_INVALIDDATA; s->curtileno = Isot; Psot = bytestream2_get_be32u(&s->g); // Psot TPsot = bytestream2_get_byteu(&s->g); // TPsot /* Read TNSot but not used */ bytestream2_get_byteu(&s->g); // TNsot if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) { av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot); return AVERROR_INVALIDDATA; } if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) { avpriv_request_sample(s->avctx, "Support for %d components", TPsot); return AVERROR_PATCHWELCOME; } s->tile[Isot].tp_idx = TPsot; tp = s->tile[Isot].tile_part + TPsot; tp->tile_index = Isot; tp->tp_end = s->g.buffer + Psot - n - 2; if (!TPsot) { Jpeg2000Tile *tile = s->tile + s->curtileno; /* copy defaults */ memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle)); memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle)); } return 0; } /* Tile-part lengths: see ISO 15444-1:2002, section A.7.1 * Used to know the number of tile parts and lengths. * There may be multiple TLMs in the header. * TODO: The function is not used for tile-parts management, nor anywhere else. * It can be useful to allocate memory for tile parts, before managing the SOT * markers. Parsing the TLM header is needed to increment the input header * buffer. * This marker is mandatory for DCI. */ static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n) { uint8_t Stlm, ST, SP, tile_tlm, i; bytestream2_get_byte(&s->g); /* Ztlm: skipped */ Stlm = bytestream2_get_byte(&s->g); // too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02); ST = (Stlm >> 4) & 0x03; // TODO: Manage case of ST = 0b11 --> raise error SP = (Stlm >> 6) & 0x01; tile_tlm = (n - 4) / ((SP + 1) * 2 + ST); for (i = 0; i < tile_tlm; i++) { switch (ST) { case 0: break; case 1: bytestream2_get_byte(&s->g); break; case 2: bytestream2_get_be16(&s->g); break; case 3: bytestream2_get_be32(&s->g); break; } if (SP == 0) { bytestream2_get_be16(&s->g); } else { bytestream2_get_be32(&s->g); } } return 0; } static int init_tile(Jpeg2000DecoderContext *s, int tileno) { int compno; int tilex = tileno % s->numXtiles; int tiley = tileno / s->numXtiles; Jpeg2000Tile *tile = s->tile + tileno; if (!tile->comp) return AVERROR(ENOMEM); for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; int ret; // global bandno comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x); comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width); comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y); comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height); comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor); comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor); comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor); comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor); if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty, s->cbps[compno], s->cdx[compno], s->cdy[compno], s->avctx)) return ret; } return 0; } /* Read the number of coding passes. */ static int getnpasses(Jpeg2000DecoderContext *s) { int num; if (!get_bits(s, 1)) return 1; if (!get_bits(s, 1)) return 2; if ((num = get_bits(s, 2)) != 3) return num < 0 ? num : 3 + num; if ((num = get_bits(s, 5)) != 31) return num < 0 ? num : 6 + num; num = get_bits(s, 7); return num < 0 ? num : 37 + num; } static int getlblockinc(Jpeg2000DecoderContext *s) { int res = 0, ret; while (ret = get_bits(s, 1)) { if (ret < 0) return ret; res++; } return res; } static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %zu", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc = ret; cblk->npasses += newpasses; } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc || sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2 ) { av_log(s->avctx, AV_LOG_ERROR, "Block length %d or lengthinc %d is too large\n", cblk->length, cblk->lengthinc); return AVERROR_INVALIDDATA; } bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } return 0; } static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int ret = 0; int layno, reslevelno, compno, precno, ok_reslevel; int x, y; s->bit_index = 8; switch (tile->codsty[0].prog_order) { case JPEG2000_PGOD_RLCP: avpriv_request_sample(s->avctx, "Progression order RLCP"); case JPEG2000_PGOD_LRCP: for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { ok_reslevel = 1; for (reslevelno = 0; ok_reslevel; reslevelno++) { ok_reslevel = 0; for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; if (reslevelno < codsty->nreslevels) { Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; ok_reslevel = 1; for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++) if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } break; case JPEG2000_PGOD_CPRL: for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000CodingStyle *codsty = tile->codsty + compno; Jpeg2000QuantStyle *qntsty = tile->qntsty + compno; /* Set bit stream buffer address according to tile-part. * For DCinema one tile-part per component, so can be * indexed by component. */ s->g = tile->tile_part[compno].tpg; /* Position loop (y axis) * TODO: Automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (y = 0; y < s->height; y += 256) { /* Position loop (y axis) * TODO: automate computing of step 256. * Fixed here, but to be computed before entering here. */ for (x = 0; x < s->width; x += 256) { for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) { uint16_t prcx, prcy; uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno; if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) || (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) || (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema continue; // check if a precinct exists prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width; prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height; precno = prcx + rlevel->num_precincts_x * prcy; for (layno = 0; layno < tile->codsty[0].nlayers; layno++) { if ((ret = jpeg2000_decode_packet(s, codsty, rlevel, precno, layno, qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0), qntsty->nguardbits)) < 0) return ret; } } } } } break; case JPEG2000_PGOD_RPCL: avpriv_request_sample(s->avctx, "Progression order RPCL"); ret = AVERROR_PATCHWELCOME; break; case JPEG2000_PGOD_PCRL: avpriv_request_sample(s->avctx, "Progression order PCRL"); ret = AVERROR_PATCHWELCOME; break; default: break; } /* EOC marker reached */ bytestream2_skip(&s->g, 2); return ret; } /* TIER-1 routines */ static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int bpass_csty_symbol, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) { if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB) && !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) { int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit); if (bpass_csty_symbol) t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask; else t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS; } } } static void decode_refpass(Jpeg2000T1Context *t1, int width, int height, int bpno) { int phalf, nhalf; int y0, x, y; phalf = 1 << (bpno - 1); nhalf = -phalf; for (y0 = 0; y0 < height; y0 += 4) for (x = 0; x < width; x++) for (y = y0; y < height && y < y0 + 4; y++) if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) { int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]); int r = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? phalf : nhalf; t1->data[y][x] += t1->data[y][x] < 0 ? -r : r; t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF; } } static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1, int width, int height, int bpno, int bandno, int seg_symbols, int vert_causal_ctx_csty_symbol) { int mask = 3 << (bpno - 1), y0, x, y, runlen, dec; for (y0 = 0; y0 < height; y0 += 4) { for (x = 0; x < width; x++) { if (y0 + 3 < height && !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) || (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) { if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL)) continue; runlen = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); dec = 1; } else { runlen = 0; dec = 0; } for (y = y0 + runlen; y < y0 + 4 && y < height; y++) { if (!dec) { if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) { int flags_mask = -1; if (vert_causal_ctx_csty_symbol && y == y0 + 3) flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE); dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno)); } } if (dec) { int xorbit; int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1], &xorbit); t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ? -mask : mask; ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0); } dec = 0; t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS; } } } if (seg_symbols) { int val; val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI); if (val != 0xa) av_log(s->avctx, AV_LOG_ERROR, "Segmentation symbol value incorrect\n"); } } static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; av_assert0(width <= JPEG2000_MAX_CBLKW); av_assert0(height <= JPEG2000_MAX_CBLKH); for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } /* TODO: Verify dequantization for lossless case * comp->data can be float or int * band->stepsize can be float or int * depending on the type of DWT transformation. * see ISO/IEC 15444-1:2002 A.6.1 */ /* Float dequantization of a codeblock.*/ static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = src[i] * band->f_stepsize; } } /* Integer dequantization of a codeblock.*/ static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk, Jpeg2000Component *comp, Jpeg2000T1Context *t1, Jpeg2000Band *band) { int i, j; int w = cblk->coord[0][1] - cblk->coord[0][0]; for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) { int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x]; int *src = t1->data[j]; for (i = 0; i < w; ++i) datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15; } } /* Inverse ICT parameters in float and integer. * int value = (float value) * (1<<16) */ static const float f_ict_params[4] = { 1.402f, 0.34413f, 0.71414f, 1.772f }; static const int i_ict_params[4] = { 91881, 22553, 46802, 116130 }; static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile) { int i, csize = 1; int32_t *src[3], i0, i1, i2; float *srcf[3], i0f, i1f, i2f; for (i = 1; i < 3; i++) if (tile->codsty[0].transform != tile->codsty[i].transform) { av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n"); return; } for (i = 0; i < 3; i++) if (tile->codsty[0].transform == FF_DWT97) srcf[i] = tile->comp[i].f_data; else src [i] = tile->comp[i].i_data; for (i = 0; i < 2; i++) csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0]; switch (tile->codsty[0].transform) { case FF_DWT97: for (i = 0; i < csize; i++) { i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]); i1f = *srcf[0] - (f_ict_params[1] * *srcf[1]) - (f_ict_params[2] * *srcf[2]); i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]); *srcf[0]++ = i0f; *srcf[1]++ = i1f; *srcf[2]++ = i2f; } break; case FF_DWT97_INT: for (i = 0; i < csize; i++) { i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16); i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16) - (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16); i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16); *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; case FF_DWT53: for (i = 0; i < csize; i++) { i1 = *src[0] - (*src[2] + *src[1] >> 2); i0 = i1 + *src[2]; i2 = i1 + *src[1]; *src[0]++ = i0; *src[1]++ = i1; *src[2]++ = i2; } break; } } static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s) { int tileno, compno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { if (s->tile[tileno].comp) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = s->tile[tileno].comp + compno; Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno; ff_jpeg2000_cleanup(comp, codsty); } av_freep(&s->tile[tileno].comp); } } av_freep(&s->tile); memset(s->codsty, 0, sizeof(s->codsty)); memset(s->qntsty, 0, sizeof(s->qntsty)); s->numXtiles = s->numYtiles = 0; } static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s) { Jpeg2000CodingStyle *codsty = s->codsty; Jpeg2000QuantStyle *qntsty = s->qntsty; uint8_t *properties = s->properties; for (;;) { int len, ret = 0; uint16_t marker; int oldpos; if (bytestream2_get_bytes_left(&s->g) < 2) { av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n"); break; } marker = bytestream2_get_be16u(&s->g); oldpos = bytestream2_tell(&s->g); if (marker == JPEG2000_SOD) { Jpeg2000Tile *tile; Jpeg2000TilePart *tp; if (!s->tile) { av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n"); return AVERROR_INVALIDDATA; } if (s->curtileno < 0) { av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n"); return AVERROR_INVALIDDATA; } tile = s->tile + s->curtileno; tp = tile->tile_part + tile->tp_idx; if (tp->tp_end < s->g.buffer) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n"); return AVERROR_INVALIDDATA; } bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer); bytestream2_skip(&s->g, tp->tp_end - s->g.buffer); continue; } if (marker == JPEG2000_EOC) break; len = bytestream2_get_be16(&s->g); if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2) return AVERROR_INVALIDDATA; switch (marker) { case JPEG2000_SIZ: ret = get_siz(s); if (!s->tile) s->numXtiles = s->numYtiles = 0; break; case JPEG2000_COC: ret = get_coc(s, codsty, properties); break; case JPEG2000_COD: ret = get_cod(s, codsty, properties); break; case JPEG2000_QCC: ret = get_qcc(s, len, qntsty, properties); break; case JPEG2000_QCD: ret = get_qcd(s, len, qntsty, properties); break; case JPEG2000_SOT: if (!(ret = get_sot(s, len))) { av_assert1(s->curtileno >= 0); codsty = s->tile[s->curtileno].codsty; qntsty = s->tile[s->curtileno].qntsty; properties = s->tile[s->curtileno].properties; } break; case JPEG2000_COM: // the comment is ignored bytestream2_skip(&s->g, len - 2); break; case JPEG2000_TLM: // Tile-part lengths ret = get_tlm(s, len); break; default: av_log(s->avctx, AV_LOG_ERROR, "unsupported marker 0x%.4X at pos 0x%X\n", marker, bytestream2_tell(&s->g) - 4); bytestream2_skip(&s->g, len - 2); break; } if (bytestream2_tell(&s->g) - oldpos != len || ret) { av_log(s->avctx, AV_LOG_ERROR, "error during processing marker segment %.4x\n", marker); return ret ? ret : -1; } } return 0; } /* Read bit stream packets --> T2 operation. */ static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s) { int ret = 0; int tileno; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) { Jpeg2000Tile *tile = s->tile + tileno; if (ret = init_tile(s, tileno)) return ret; s->g = tile->tile_part[0].tpg; if (ret = jpeg2000_decode_packets(s, tile)) return ret; } return 0; } static int jp2_find_codestream(Jpeg2000DecoderContext *s) { uint32_t atom_size, atom, atom_end; int search_range = 10; while (search_range && bytestream2_get_bytes_left(&s->g) >= 8) { atom_size = bytestream2_get_be32u(&s->g); atom = bytestream2_get_be32u(&s->g); atom_end = bytestream2_tell(&s->g) + atom_size - 8; if (atom == JP2_CODESTREAM) return 1; if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size) return 0; if (atom == JP2_HEADER && atom_size >= 16) { uint32_t atom2_size, atom2, atom2_end; do { atom2_size = bytestream2_get_be32u(&s->g); atom2 = bytestream2_get_be32u(&s->g); atom2_end = bytestream2_tell(&s->g) + atom2_size - 8; if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size) break; if (atom2 == JP2_CODESTREAM) { return 1; } else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) { int method = bytestream2_get_byteu(&s->g); bytestream2_skipu(&s->g, 2); if (method == 1) { s->colour_space = bytestream2_get_be32u(&s->g); } } else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) { int i, size, colour_count, colour_channels, colour_depth[3]; uint32_t r, g, b; colour_count = bytestream2_get_be16u(&s->g); colour_channels = bytestream2_get_byteu(&s->g); // FIXME: Do not ignore channel_sign colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1; size = (colour_depth[0] + 7 >> 3) * colour_count + (colour_depth[1] + 7 >> 3) * colour_count + (colour_depth[2] + 7 >> 3) * colour_count; if (colour_count > 256 || colour_channels != 3 || colour_depth[0] > 16 || colour_depth[1] > 16 || colour_depth[2] > 16 || atom2_size < size) { avpriv_request_sample(s->avctx, "Unknown palette"); bytestream2_seek(&s->g, atom2_end, SEEK_SET); continue; } s->pal8 = 1; for (i = 0; i < colour_count; i++) { if (colour_depth[0] <= 8) { r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0]; r |= r >> colour_depth[0]; } else { r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8; } if (colour_depth[1] <= 8) { g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1]; r |= r >> colour_depth[1]; } else { g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8; } if (colour_depth[2] <= 8) { b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2]; r |= r >> colour_depth[2]; } else { b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8; } s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b; } } else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) { int n = bytestream2_get_be16u(&s->g); for (; n>0; n--) { int cn = bytestream2_get_be16(&s->g); int av_unused typ = bytestream2_get_be16(&s->g); int asoc = bytestream2_get_be16(&s->g); if (cn < 4 || asoc < 4) s->cdef[cn] = asoc; } } bytestream2_seek(&s->g, atom2_end, SEEK_SET); } while (atom_end - atom2_end >= 8); } else { search_range--; } bytestream2_seek(&s->g, atom_end, SEEK_SET); } return 0; } static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { Jpeg2000DecoderContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; int tileno, ret; s->avctx = avctx; bytestream2_init(&s->g, avpkt->data, avpkt->size); s->curtileno = -1; memset(s->cdef, -1, sizeof(s->cdef)); if (bytestream2_get_bytes_left(&s->g) < 2) { ret = AVERROR_INVALIDDATA; goto end; } // check if the image is in jp2 format if (bytestream2_get_bytes_left(&s->g) >= 12 && (bytestream2_get_be32u(&s->g) == 12) && (bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) && (bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) { if (!jp2_find_codestream(s)) { av_log(avctx, AV_LOG_ERROR, "Could not find Jpeg2000 codestream atom.\n"); ret = AVERROR_INVALIDDATA; goto end; } } else { bytestream2_seek(&s->g, 0, SEEK_SET); } while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC) bytestream2_skip(&s->g, 1); if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) { av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n"); ret = AVERROR_INVALIDDATA; goto end; } if (ret = jpeg2000_read_main_headers(s)) goto end; /* get picture buffer */ if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) goto end; picture->pict_type = AV_PICTURE_TYPE_I; picture->key_frame = 1; if (ret = jpeg2000_read_bitstream_packets(s)) goto end; for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture)) goto end; jpeg2000_dec_cleanup(s); *got_frame = 1; if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8) memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t)); return bytestream2_tell(&s->g); end: jpeg2000_dec_cleanup(s); return ret; } static void jpeg2000_init_static_data(AVCodec *codec) { ff_jpeg2000_init_tier1_luts(); ff_mqc_init_context_tables(); } #define OFFSET(x) offsetof(Jpeg2000DecoderContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "lowres", "Lower the decoding resolution by a power of two", OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD }, { NULL }, }; static const AVProfile profiles[] = { { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" }, { FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" }, { FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" }, { FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" }, { FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" }, { FF_PROFILE_UNKNOWN }, }; static const AVClass jpeg2000_class = { .class_name = "jpeg2000", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_jpeg2000_decoder = { .name = "jpeg2000", .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_JPEG2000, .capabilities = CODEC_CAP_FRAME_THREADS, .priv_data_size = sizeof(Jpeg2000DecoderContext), .init_static_data = jpeg2000_init_static_data, .decode = jpeg2000_decode_frame, .priv_class = &jpeg2000_class, .max_lowres = 5, .profiles = NULL_IF_CONFIG_SMALL(profiles) };
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; }
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; }
{'added': [(1281, ' line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane];'), (1286, ' dst = line + x / s->cdx[compno] * pixelsize + compno*!planar;'), (1327, ' linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1);'), (1332, ' dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar);')], 'deleted': [(1281, ' line = picture->data[plane] + y * picture->linesize[plane];'), (1286, ' dst = line + x * pixelsize + compno*!planar;'), (1327, ' linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);'), (1332, ' dst = linel + (x * pixelsize + compno*!planar);')]}
4
4
1,372
11,523
https://github.com/FFmpeg/FFmpeg
CVE-2013-7024
['CWE-119']
cdf.c
cdf_read_property_info
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.115 2019/08/23 14:29:14 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.116 2019/08/26 14:31:39 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == %" SIZE_T_FORMAT "u\n", nelements)); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; }
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == %" SIZE_T_FORMAT "u\n", nelements)); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; }
{'added': [(38, 'FILE_RCSID("@(#)$File: cdf.c,v 1.116 2019/08/26 14:31:39 christos Exp $")'), (1030, '\t\t\tif (nelements > CDF_ELEMENT_LIMIT || nelements == 0) {'), (1031, '\t\t\t\tDPRINTF(("CDF_VECTOR with nelements == %"'), (1032, '\t\t\t\t SIZE_T_FORMAT "u\\n", nelements));')], 'deleted': [(38, 'FILE_RCSID("@(#)$File: cdf.c,v 1.115 2019/08/23 14:29:14 christos Exp $")'), (1030, '\t\t\tif (nelements == 0) {'), (1031, '\t\t\t\tDPRINTF(("CDF_VECTOR with nelements == 0\\n"));'), (1073, '\t\t\tDPRINTF(("nelements = %" SIZE_T_FORMAT "u\\n",'), (1074, '\t\t\t nelements));')]}
4
5
1,356
9,707
https://github.com/file/file
CVE-2019-18218
['CWE-787']
update.c
update_prepare_order_info
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp, UINT32 flags) { BYTE* newMask; UINT32 scanlineSize; UINT32 max = 32; if (flags & LARGE_POINTER_FLAG_96x96) max = 96; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > max) || (pointer_color->height > max)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp, update->context->settings->LargePointerFlag)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 20) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT32(s, pointer->lengthAndMask); /* lengthAndMask (4 bytes) */ Stream_Read_UINT32(s, pointer->lengthXorMask); /* lengthXorMask (4 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp, update->context->settings->LargePointerFlag)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", update_type_to_string(updateType)); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp, UINT32 flags) { BYTE* newMask; UINT32 scanlineSize; UINT32 max = 32; if (flags & LARGE_POINTER_FLAG_96x96) max = 96; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > max) || (pointer_color->height > max)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp, update->context->settings->LargePointerFlag)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 20) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT32(s, pointer->lengthAndMask); /* lengthAndMask (4 bytes) */ Stream_Read_UINT32(s, pointer->lengthXorMask); /* lengthXorMask (4 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp, update->context->settings->LargePointerFlag)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", update_type_to_string(updateType)); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL); length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL)); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; }
static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL); length += update_prepare_bounds(context, orderInfo); return length; }
{'added': [(1090, '\tlength += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL);'), (1108, '\t get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL));')], 'deleted': [(1090, '\tlength += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType];'), (1108, '\t PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]);')]}
2
2
2,326
14,322
https://github.com/FreeRDP/FreeRDP
CVE-2020-11095
['CWE-125']
update.c
update_write_order_info
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp, UINT32 flags) { BYTE* newMask; UINT32 scanlineSize; UINT32 max = 32; if (flags & LARGE_POINTER_FLAG_96x96) max = 96; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > max) || (pointer_color->height > max)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp, update->context->settings->LargePointerFlag)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 20) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT32(s, pointer->lengthAndMask); /* lengthAndMask (4 bytes) */ Stream_Read_UINT32(s, pointer->lengthXorMask); /* lengthXorMask (4 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp, update->context->settings->LargePointerFlag)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", update_type_to_string(updateType)); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp, UINT32 flags) { BYTE* newMask; UINT32 scanlineSize; UINT32 max = 32; if (flags & LARGE_POINTER_FLAG_96x96) max = 96; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > max) || (pointer_color->height > max)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp, update->context->settings->LargePointerFlag)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 20) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT32(s, pointer->lengthAndMask); /* lengthAndMask (4 bytes) */ Stream_Read_UINT32(s, pointer->lengthXorMask); /* lengthXorMask (4 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp, update->context->settings->LargePointerFlag)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", update_type_to_string(updateType)); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL); length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL)); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; }
static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL)); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; }
{'added': [(1090, '\tlength += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL);'), (1108, '\t get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL));')], 'deleted': [(1090, '\tlength += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType];'), (1108, '\t PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]);')]}
2
2
2,326
14,322
https://github.com/FreeRDP/FreeRDP
CVE-2020-11095
['CWE-125']
task_mmu.c
m_stop
#include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/huge_mm.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/highmem.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/mempolicy.h> #include <linux/rmap.h> #include <linux/swap.h> #include <linux/swapops.h> #include <asm/elf.h> #include <asm/uaccess.h> #include <asm/tlbflush.h> #include "internal.h" void task_mem(struct seq_file *m, struct mm_struct *mm) { unsigned long data, text, lib, swap; unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss; /* * Note: to minimize their overhead, mm maintains hiwater_vm and * hiwater_rss only when about to *lower* total_vm or rss. Any * collector of these hiwater stats must therefore get total_vm * and rss too, which will usually be the higher. Barriers? not * worth the effort, such snapshots can always be inconsistent. */ hiwater_vm = total_vm = mm->total_vm; if (hiwater_vm < mm->hiwater_vm) hiwater_vm = mm->hiwater_vm; hiwater_rss = total_rss = get_mm_rss(mm); if (hiwater_rss < mm->hiwater_rss) hiwater_rss = mm->hiwater_rss; data = mm->total_vm - mm->shared_vm - mm->stack_vm; text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> 10; lib = (mm->exec_vm << (PAGE_SHIFT-10)) - text; swap = get_mm_counter(mm, MM_SWAPENTS); seq_printf(m, "VmPeak:\t%8lu kB\n" "VmSize:\t%8lu kB\n" "VmLck:\t%8lu kB\n" "VmHWM:\t%8lu kB\n" "VmRSS:\t%8lu kB\n" "VmData:\t%8lu kB\n" "VmStk:\t%8lu kB\n" "VmExe:\t%8lu kB\n" "VmLib:\t%8lu kB\n" "VmPTE:\t%8lu kB\n" "VmSwap:\t%8lu kB\n", hiwater_vm << (PAGE_SHIFT-10), (total_vm - mm->reserved_vm) << (PAGE_SHIFT-10), mm->locked_vm << (PAGE_SHIFT-10), hiwater_rss << (PAGE_SHIFT-10), total_rss << (PAGE_SHIFT-10), data << (PAGE_SHIFT-10), mm->stack_vm << (PAGE_SHIFT-10), text, lib, (PTRS_PER_PTE*sizeof(pte_t)*mm->nr_ptes) >> 10, swap << (PAGE_SHIFT-10)); } unsigned long task_vsize(struct mm_struct *mm) { return PAGE_SIZE * mm->total_vm; } unsigned long task_statm(struct mm_struct *mm, unsigned long *shared, unsigned long *text, unsigned long *data, unsigned long *resident) { *shared = get_mm_counter(mm, MM_FILEPAGES); *text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> PAGE_SHIFT; *data = mm->total_vm - mm->shared_vm; *resident = *shared + get_mm_counter(mm, MM_ANONPAGES); return mm->total_vm; } static void pad_len_spaces(struct seq_file *m, int len) { len = 25 + sizeof(void*) * 6 - len; if (len < 1) len = 1; seq_printf(m, "%*c", len, ' '); } static void vma_stop(struct proc_maps_private *priv, struct vm_area_struct *vma) { if (vma && vma != priv->tail_vma) { struct mm_struct *mm = vma->vm_mm; up_read(&mm->mmap_sem); mmput(mm); } } static void *m_start(struct seq_file *m, loff_t *pos) { struct proc_maps_private *priv = m->private; unsigned long last_addr = m->version; struct mm_struct *mm; struct vm_area_struct *vma, *tail_vma = NULL; loff_t l = *pos; /* Clear the per syscall fields in priv */ priv->task = NULL; priv->tail_vma = NULL; /* * We remember last_addr rather than next_addr to hit with * mmap_cache most of the time. We have zero last_addr at * the beginning and also after lseek. We will have -1 last_addr * after the end of the vmas. */ if (last_addr == -1UL) return NULL; priv->task = get_pid_task(priv->pid, PIDTYPE_PID); if (!priv->task) return ERR_PTR(-ESRCH); mm = mm_for_maps(priv->task); if (!mm || IS_ERR(mm)) return mm; down_read(&mm->mmap_sem); tail_vma = get_gate_vma(priv->task->mm); priv->tail_vma = tail_vma; /* Start with last addr hint */ vma = find_vma(mm, last_addr); if (last_addr && vma) { vma = vma->vm_next; goto out; } /* * Check the vma index is within the range and do * sequential scan until m_index. */ vma = NULL; if ((unsigned long)l < mm->map_count) { vma = mm->mmap; while (l-- && vma) vma = vma->vm_next; goto out; } if (l != mm->map_count) tail_vma = NULL; /* After gate vma */ out: if (vma) return vma; /* End of vmas has been reached */ m->version = (tail_vma != NULL)? 0: -1UL; up_read(&mm->mmap_sem); mmput(mm); return tail_vma; } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; struct vm_area_struct *tail_vma = priv->tail_vma; (*pos)++; if (vma && (vma != tail_vma) && vma->vm_next) return vma->vm_next; vma_stop(priv, vma); return (vma != tail_vma)? tail_vma: NULL; } static void m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); } static int do_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops) { struct proc_maps_private *priv; int ret = -ENOMEM; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (priv) { priv->pid = proc_pid(inode); ret = seq_open(file, ops); if (!ret) { struct seq_file *m = file->private_data; m->private = priv; } else { kfree(priv); } } return ret; } static void show_map_vma(struct seq_file *m, struct vm_area_struct *vma) { struct mm_struct *mm = vma->vm_mm; struct file *file = vma->vm_file; int flags = vma->vm_flags; unsigned long ino = 0; unsigned long long pgoff = 0; unsigned long start; dev_t dev = 0; int len; if (file) { struct inode *inode = vma->vm_file->f_path.dentry->d_inode; dev = inode->i_sb->s_dev; ino = inode->i_ino; pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT; } /* We don't show the stack guard page in /proc/maps */ start = vma->vm_start; if (vma->vm_flags & VM_GROWSDOWN) if (!vma_stack_continue(vma->vm_prev, vma->vm_start)) start += PAGE_SIZE; seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu %n", start, vma->vm_end, flags & VM_READ ? 'r' : '-', flags & VM_WRITE ? 'w' : '-', flags & VM_EXEC ? 'x' : '-', flags & VM_MAYSHARE ? 's' : 'p', pgoff, MAJOR(dev), MINOR(dev), ino, &len); /* * Print the dentry name for named mappings, and a * special [heap] marker for the heap: */ if (file) { pad_len_spaces(m, len); seq_path(m, &file->f_path, "\n"); } else { const char *name = arch_vma_name(vma); if (!name) { if (mm) { if (vma->vm_start <= mm->brk && vma->vm_end >= mm->start_brk) { name = "[heap]"; } else if (vma->vm_start <= mm->start_stack && vma->vm_end >= mm->start_stack) { name = "[stack]"; } } else { name = "[vdso]"; } } if (name) { pad_len_spaces(m, len); seq_puts(m, name); } } seq_putc(m, '\n'); } static int show_map(struct seq_file *m, void *v) { struct vm_area_struct *vma = v; struct proc_maps_private *priv = m->private; struct task_struct *task = priv->task; show_map_vma(m, vma); if (m->count < m->size) /* vma is copied successfully */ m->version = (vma != get_gate_vma(task->mm)) ? vma->vm_start : 0; return 0; } static const struct seq_operations proc_pid_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_map }; static int maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_maps_op); } const struct file_operations proc_maps_operations = { .open = maps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; /* * Proportional Set Size(PSS): my share of RSS. * * PSS of a process is the count of pages it has in memory, where each * page is divided by the number of processes sharing it. So if a * process has 1000 pages all to itself, and 1000 shared with one other * process, its PSS will be 1500. * * To keep (accumulated) division errors low, we adopt a 64bit * fixed-point pss counter to minimize division errors. So (pss >> * PSS_SHIFT) would be the real byte count. * * A shift of 12 before division means (assuming 4K page size): * - 1M 3-user-pages add up to 8KB errors; * - supports mapcount up to 2^24, or 16M; * - supports PSS up to 2^52 bytes, or 4PB. */ #define PSS_SHIFT 12 #ifdef CONFIG_PROC_PAGE_MONITOR struct mem_size_stats { struct vm_area_struct *vma; unsigned long resident; unsigned long shared_clean; unsigned long shared_dirty; unsigned long private_clean; unsigned long private_dirty; unsigned long referenced; unsigned long anonymous; unsigned long anonymous_thp; unsigned long swap; u64 pss; }; static void smaps_pte_entry(pte_t ptent, unsigned long addr, unsigned long ptent_size, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = mss->vma; struct page *page; int mapcount; if (is_swap_pte(ptent)) { mss->swap += ptent_size; return; } if (!pte_present(ptent)) return; page = vm_normal_page(vma, addr, ptent); if (!page) return; if (PageAnon(page)) mss->anonymous += ptent_size; mss->resident += ptent_size; /* Accumulate the size in pages that have been accessed. */ if (pte_young(ptent) || PageReferenced(page)) mss->referenced += ptent_size; mapcount = page_mapcount(page); if (mapcount >= 2) { if (pte_dirty(ptent) || PageDirty(page)) mss->shared_dirty += ptent_size; else mss->shared_clean += ptent_size; mss->pss += (ptent_size << PSS_SHIFT) / mapcount; } else { if (pte_dirty(ptent) || PageDirty(page)) mss->private_dirty += ptent_size; else mss->private_clean += ptent_size; mss->pss += (ptent_size << PSS_SHIFT); } } static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = mss->vma; pte_t *pte; spinlock_t *ptl; spin_lock(&walk->mm->page_table_lock); if (pmd_trans_huge(*pmd)) { if (pmd_trans_splitting(*pmd)) { spin_unlock(&walk->mm->page_table_lock); wait_split_huge_page(vma->anon_vma, pmd); } else { smaps_pte_entry(*(pte_t *)pmd, addr, HPAGE_PMD_SIZE, walk); spin_unlock(&walk->mm->page_table_lock); mss->anonymous_thp += HPAGE_PMD_SIZE; return 0; } } else { spin_unlock(&walk->mm->page_table_lock); } /* * The mmap_sem held all the way back in m_start() is what * keeps khugepaged out of here and from collapsing things * in here. */ pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) smaps_pte_entry(*pte, addr, PAGE_SIZE, walk); pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } static int show_smap(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct task_struct *task = priv->task; struct vm_area_struct *vma = v; struct mem_size_stats mss; struct mm_walk smaps_walk = { .pmd_entry = smaps_pte_range, .mm = vma->vm_mm, .private = &mss, }; memset(&mss, 0, sizeof mss); mss.vma = vma; /* mmap_sem is held in m_start */ if (vma->vm_mm && !is_vm_hugetlb_page(vma)) walk_page_range(vma->vm_start, vma->vm_end, &smaps_walk); show_map_vma(m, vma); seq_printf(m, "Size: %8lu kB\n" "Rss: %8lu kB\n" "Pss: %8lu kB\n" "Shared_Clean: %8lu kB\n" "Shared_Dirty: %8lu kB\n" "Private_Clean: %8lu kB\n" "Private_Dirty: %8lu kB\n" "Referenced: %8lu kB\n" "Anonymous: %8lu kB\n" "AnonHugePages: %8lu kB\n" "Swap: %8lu kB\n" "KernelPageSize: %8lu kB\n" "MMUPageSize: %8lu kB\n" "Locked: %8lu kB\n", (vma->vm_end - vma->vm_start) >> 10, mss.resident >> 10, (unsigned long)(mss.pss >> (10 + PSS_SHIFT)), mss.shared_clean >> 10, mss.shared_dirty >> 10, mss.private_clean >> 10, mss.private_dirty >> 10, mss.referenced >> 10, mss.anonymous >> 10, mss.anonymous_thp >> 10, mss.swap >> 10, vma_kernel_pagesize(vma) >> 10, vma_mmu_pagesize(vma) >> 10, (vma->vm_flags & VM_LOCKED) ? (unsigned long)(mss.pss >> (10 + PSS_SHIFT)) : 0); if (m->count < m->size) /* vma is copied successfully */ m->version = (vma != get_gate_vma(task->mm)) ? vma->vm_start : 0; return 0; } static const struct seq_operations proc_pid_smaps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_smap }; static int smaps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_smaps_op); } const struct file_operations proc_smaps_operations = { .open = smaps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->private; pte_t *pte, ptent; spinlock_t *ptl; struct page *page; split_huge_page_pmd(walk->mm, pmd); pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) { ptent = *pte; if (!pte_present(ptent)) continue; page = vm_normal_page(vma, addr, ptent); if (!page) continue; /* Clear accessed and referenced bits. */ ptep_test_and_clear_young(vma, addr, pte); ClearPageReferenced(page); } pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } #define CLEAR_REFS_ALL 1 #define CLEAR_REFS_ANON 2 #define CLEAR_REFS_MAPPED 3 static ssize_t clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; long type; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; if (strict_strtol(strstrip(buffer), 10, &type)) return -EINVAL; if (type < CLEAR_REFS_ALL || type > CLEAR_REFS_MAPPED) return -EINVAL; task = get_proc_task(file->f_path.dentry->d_inode); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .mm = mm, }; down_read(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) { clear_refs_walk.private = vma; if (is_vm_hugetlb_page(vma)) continue; /* * Writing 1 to /proc/pid/clear_refs affects all pages. * * Writing 2 to /proc/pid/clear_refs only affects * Anonymous pages. * * Writing 3 to /proc/pid/clear_refs only affects file * mapped pages. */ if (type == CLEAR_REFS_ANON && vma->vm_file) continue; if (type == CLEAR_REFS_MAPPED && !vma->vm_file) continue; walk_page_range(vma->vm_start, vma->vm_end, &clear_refs_walk); } flush_tlb_mm(mm); up_read(&mm->mmap_sem); mmput(mm); } put_task_struct(task); return count; } const struct file_operations proc_clear_refs_operations = { .write = clear_refs_write, .llseek = noop_llseek, }; struct pagemapread { int pos, len; u64 *buffer; }; #define PM_ENTRY_BYTES sizeof(u64) #define PM_STATUS_BITS 3 #define PM_STATUS_OFFSET (64 - PM_STATUS_BITS) #define PM_STATUS_MASK (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET) #define PM_STATUS(nr) (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK) #define PM_PSHIFT_BITS 6 #define PM_PSHIFT_OFFSET (PM_STATUS_OFFSET - PM_PSHIFT_BITS) #define PM_PSHIFT_MASK (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET) #define PM_PSHIFT(x) (((u64) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK) #define PM_PFRAME_MASK ((1LL << PM_PSHIFT_OFFSET) - 1) #define PM_PFRAME(x) ((x) & PM_PFRAME_MASK) #define PM_PRESENT PM_STATUS(4LL) #define PM_SWAP PM_STATUS(2LL) #define PM_NOT_PRESENT PM_PSHIFT(PAGE_SHIFT) #define PM_END_OF_BUFFER 1 static int add_to_pagemap(unsigned long addr, u64 pfn, struct pagemapread *pm) { pm->buffer[pm->pos++] = pfn; if (pm->pos >= pm->len) return PM_END_OF_BUFFER; return 0; } static int pagemap_pte_hole(unsigned long start, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; unsigned long addr; int err = 0; for (addr = start; addr < end; addr += PAGE_SIZE) { err = add_to_pagemap(addr, PM_NOT_PRESENT, pm); if (err) break; } return err; } static u64 swap_pte_to_pagemap_entry(pte_t pte) { swp_entry_t e = pte_to_swp_entry(pte); return swp_type(e) | (swp_offset(e) << MAX_SWAPFILES_SHIFT); } static u64 pte_to_pagemap_entry(pte_t pte) { u64 pme = 0; if (is_swap_pte(pte)) pme = PM_PFRAME(swap_pte_to_pagemap_entry(pte)) | PM_PSHIFT(PAGE_SHIFT) | PM_SWAP; else if (pte_present(pte)) pme = PM_PFRAME(pte_pfn(pte)) | PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT; return pme; } static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma; struct pagemapread *pm = walk->private; pte_t *pte; int err = 0; split_huge_page_pmd(walk->mm, pmd); /* find the first VMA at or above 'addr' */ vma = find_vma(walk->mm, addr); for (; addr != end; addr += PAGE_SIZE) { u64 pfn = PM_NOT_PRESENT; /* check to see if we've left 'vma' behind * and need a new, higher one */ if (vma && (addr >= vma->vm_end)) vma = find_vma(walk->mm, addr); /* check that 'vma' actually covers this address, * and that it isn't a huge page vma */ if (vma && (vma->vm_start <= addr) && !is_vm_hugetlb_page(vma)) { pte = pte_offset_map(pmd, addr); pfn = pte_to_pagemap_entry(*pte); /* unmap before userspace copy */ pte_unmap(pte); } err = add_to_pagemap(addr, pfn, pm); if (err) return err; } cond_resched(); return err; } #ifdef CONFIG_HUGETLB_PAGE static u64 huge_pte_to_pagemap_entry(pte_t pte, int offset) { u64 pme = 0; if (pte_present(pte)) pme = PM_PFRAME(pte_pfn(pte) + offset) | PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT; return pme; } /* This function walks within one hugetlb entry in the single call */ static int pagemap_hugetlb_range(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; int err = 0; u64 pfn; for (; addr != end; addr += PAGE_SIZE) { int offset = (addr & ~hmask) >> PAGE_SHIFT; pfn = huge_pte_to_pagemap_entry(*pte, offset); err = add_to_pagemap(addr, pfn, pm); if (err) return err; } cond_resched(); return err; } #endif /* HUGETLB_PAGE */ /* * /proc/pid/pagemap - an array mapping virtual pages to pfns * * For each page in the address space, this file contains one 64-bit entry * consisting of the following: * * Bits 0-55 page frame number (PFN) if present * Bits 0-4 swap type if swapped * Bits 5-55 swap offset if swapped * Bits 55-60 page shift (page size = 1<<page shift) * Bit 61 reserved for future use * Bit 62 page swapped * Bit 63 page present * * If the page is not present but in swap, then the PFN contains an * encoding of the swap file number and the page's offset into the * swap. Unmapped pages return a null PFN. This allows determining * precisely which pages are mapped (or in swap) and comparing mapped * pages between processes. * * Efficient users of this interface will use /proc/pid/maps to * determine which areas of memory are actually mapped and llseek to * skip over unmapped regions. */ #define PAGEMAP_WALK_SIZE (PMD_SIZE) #define PAGEMAP_WALK_MASK (PMD_MASK) static ssize_t pagemap_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode); struct mm_struct *mm; struct pagemapread pm; int ret = -ESRCH; struct mm_walk pagemap_walk = {}; unsigned long src; unsigned long svpfn; unsigned long start_vaddr; unsigned long end_vaddr; int copied = 0; if (!task) goto out; mm = mm_for_maps(task); ret = PTR_ERR(mm); if (!mm || IS_ERR(mm)) goto out_task; ret = -EINVAL; /* file position must be aligned */ if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES)) goto out_task; ret = 0; if (!count) goto out_task; pm.len = PM_ENTRY_BYTES * (PAGEMAP_WALK_SIZE >> PAGE_SHIFT); pm.buffer = kmalloc(pm.len, GFP_TEMPORARY); ret = -ENOMEM; if (!pm.buffer) goto out_mm; pagemap_walk.pmd_entry = pagemap_pte_range; pagemap_walk.pte_hole = pagemap_pte_hole; #ifdef CONFIG_HUGETLB_PAGE pagemap_walk.hugetlb_entry = pagemap_hugetlb_range; #endif pagemap_walk.mm = mm; pagemap_walk.private = &pm; src = *ppos; svpfn = src / PM_ENTRY_BYTES; start_vaddr = svpfn << PAGE_SHIFT; end_vaddr = TASK_SIZE_OF(task); /* watch out for wraparound */ if (svpfn > TASK_SIZE_OF(task) >> PAGE_SHIFT) start_vaddr = end_vaddr; /* * The odds are that this will stop walking way * before end_vaddr, because the length of the * user buffer is tracked in "pm", and the walk * will stop when we hit the end of the buffer. */ ret = 0; while (count && (start_vaddr < end_vaddr)) { int len; unsigned long end; pm.pos = 0; end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK; /* overflow ? */ if (end < start_vaddr || end > end_vaddr) end = end_vaddr; down_read(&mm->mmap_sem); ret = walk_page_range(start_vaddr, end, &pagemap_walk); up_read(&mm->mmap_sem); start_vaddr = end; len = min(count, PM_ENTRY_BYTES * pm.pos); if (copy_to_user(buf, pm.buffer, len)) { ret = -EFAULT; goto out_free; } copied += len; buf += len; count -= len; } *ppos += copied; if (!ret || ret == PM_END_OF_BUFFER) ret = copied; out_free: kfree(pm.buffer); out_mm: mmput(mm); out_task: put_task_struct(task); out: return ret; } const struct file_operations proc_pagemap_operations = { .llseek = mem_lseek, /* borrow this */ .read = pagemap_read, }; #endif /* CONFIG_PROC_PAGE_MONITOR */ #ifdef CONFIG_NUMA extern int show_numa_map(struct seq_file *m, void *v); static const struct seq_operations proc_pid_numa_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_numa_map, }; static int numa_maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_numa_maps_op); } const struct file_operations proc_numa_maps_operations = { .open = numa_maps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; #endif
#include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/huge_mm.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/highmem.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/mempolicy.h> #include <linux/rmap.h> #include <linux/swap.h> #include <linux/swapops.h> #include <asm/elf.h> #include <asm/uaccess.h> #include <asm/tlbflush.h> #include "internal.h" void task_mem(struct seq_file *m, struct mm_struct *mm) { unsigned long data, text, lib, swap; unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss; /* * Note: to minimize their overhead, mm maintains hiwater_vm and * hiwater_rss only when about to *lower* total_vm or rss. Any * collector of these hiwater stats must therefore get total_vm * and rss too, which will usually be the higher. Barriers? not * worth the effort, such snapshots can always be inconsistent. */ hiwater_vm = total_vm = mm->total_vm; if (hiwater_vm < mm->hiwater_vm) hiwater_vm = mm->hiwater_vm; hiwater_rss = total_rss = get_mm_rss(mm); if (hiwater_rss < mm->hiwater_rss) hiwater_rss = mm->hiwater_rss; data = mm->total_vm - mm->shared_vm - mm->stack_vm; text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> 10; lib = (mm->exec_vm << (PAGE_SHIFT-10)) - text; swap = get_mm_counter(mm, MM_SWAPENTS); seq_printf(m, "VmPeak:\t%8lu kB\n" "VmSize:\t%8lu kB\n" "VmLck:\t%8lu kB\n" "VmHWM:\t%8lu kB\n" "VmRSS:\t%8lu kB\n" "VmData:\t%8lu kB\n" "VmStk:\t%8lu kB\n" "VmExe:\t%8lu kB\n" "VmLib:\t%8lu kB\n" "VmPTE:\t%8lu kB\n" "VmSwap:\t%8lu kB\n", hiwater_vm << (PAGE_SHIFT-10), (total_vm - mm->reserved_vm) << (PAGE_SHIFT-10), mm->locked_vm << (PAGE_SHIFT-10), hiwater_rss << (PAGE_SHIFT-10), total_rss << (PAGE_SHIFT-10), data << (PAGE_SHIFT-10), mm->stack_vm << (PAGE_SHIFT-10), text, lib, (PTRS_PER_PTE*sizeof(pte_t)*mm->nr_ptes) >> 10, swap << (PAGE_SHIFT-10)); } unsigned long task_vsize(struct mm_struct *mm) { return PAGE_SIZE * mm->total_vm; } unsigned long task_statm(struct mm_struct *mm, unsigned long *shared, unsigned long *text, unsigned long *data, unsigned long *resident) { *shared = get_mm_counter(mm, MM_FILEPAGES); *text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> PAGE_SHIFT; *data = mm->total_vm - mm->shared_vm; *resident = *shared + get_mm_counter(mm, MM_ANONPAGES); return mm->total_vm; } static void pad_len_spaces(struct seq_file *m, int len) { len = 25 + sizeof(void*) * 6 - len; if (len < 1) len = 1; seq_printf(m, "%*c", len, ' '); } static void vma_stop(struct proc_maps_private *priv, struct vm_area_struct *vma) { if (vma && vma != priv->tail_vma) { struct mm_struct *mm = vma->vm_mm; up_read(&mm->mmap_sem); mmput(mm); } } static void *m_start(struct seq_file *m, loff_t *pos) { struct proc_maps_private *priv = m->private; unsigned long last_addr = m->version; struct mm_struct *mm; struct vm_area_struct *vma, *tail_vma = NULL; loff_t l = *pos; /* Clear the per syscall fields in priv */ priv->task = NULL; priv->tail_vma = NULL; /* * We remember last_addr rather than next_addr to hit with * mmap_cache most of the time. We have zero last_addr at * the beginning and also after lseek. We will have -1 last_addr * after the end of the vmas. */ if (last_addr == -1UL) return NULL; priv->task = get_pid_task(priv->pid, PIDTYPE_PID); if (!priv->task) return ERR_PTR(-ESRCH); mm = mm_for_maps(priv->task); if (!mm || IS_ERR(mm)) return mm; down_read(&mm->mmap_sem); tail_vma = get_gate_vma(priv->task->mm); priv->tail_vma = tail_vma; /* Start with last addr hint */ vma = find_vma(mm, last_addr); if (last_addr && vma) { vma = vma->vm_next; goto out; } /* * Check the vma index is within the range and do * sequential scan until m_index. */ vma = NULL; if ((unsigned long)l < mm->map_count) { vma = mm->mmap; while (l-- && vma) vma = vma->vm_next; goto out; } if (l != mm->map_count) tail_vma = NULL; /* After gate vma */ out: if (vma) return vma; /* End of vmas has been reached */ m->version = (tail_vma != NULL)? 0: -1UL; up_read(&mm->mmap_sem); mmput(mm); return tail_vma; } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; struct vm_area_struct *tail_vma = priv->tail_vma; (*pos)++; if (vma && (vma != tail_vma) && vma->vm_next) return vma->vm_next; vma_stop(priv, vma); return (vma != tail_vma)? tail_vma: NULL; } static void m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; if (!IS_ERR(vma)) vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); } static int do_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops) { struct proc_maps_private *priv; int ret = -ENOMEM; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (priv) { priv->pid = proc_pid(inode); ret = seq_open(file, ops); if (!ret) { struct seq_file *m = file->private_data; m->private = priv; } else { kfree(priv); } } return ret; } static void show_map_vma(struct seq_file *m, struct vm_area_struct *vma) { struct mm_struct *mm = vma->vm_mm; struct file *file = vma->vm_file; int flags = vma->vm_flags; unsigned long ino = 0; unsigned long long pgoff = 0; unsigned long start; dev_t dev = 0; int len; if (file) { struct inode *inode = vma->vm_file->f_path.dentry->d_inode; dev = inode->i_sb->s_dev; ino = inode->i_ino; pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT; } /* We don't show the stack guard page in /proc/maps */ start = vma->vm_start; if (vma->vm_flags & VM_GROWSDOWN) if (!vma_stack_continue(vma->vm_prev, vma->vm_start)) start += PAGE_SIZE; seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu %n", start, vma->vm_end, flags & VM_READ ? 'r' : '-', flags & VM_WRITE ? 'w' : '-', flags & VM_EXEC ? 'x' : '-', flags & VM_MAYSHARE ? 's' : 'p', pgoff, MAJOR(dev), MINOR(dev), ino, &len); /* * Print the dentry name for named mappings, and a * special [heap] marker for the heap: */ if (file) { pad_len_spaces(m, len); seq_path(m, &file->f_path, "\n"); } else { const char *name = arch_vma_name(vma); if (!name) { if (mm) { if (vma->vm_start <= mm->brk && vma->vm_end >= mm->start_brk) { name = "[heap]"; } else if (vma->vm_start <= mm->start_stack && vma->vm_end >= mm->start_stack) { name = "[stack]"; } } else { name = "[vdso]"; } } if (name) { pad_len_spaces(m, len); seq_puts(m, name); } } seq_putc(m, '\n'); } static int show_map(struct seq_file *m, void *v) { struct vm_area_struct *vma = v; struct proc_maps_private *priv = m->private; struct task_struct *task = priv->task; show_map_vma(m, vma); if (m->count < m->size) /* vma is copied successfully */ m->version = (vma != get_gate_vma(task->mm)) ? vma->vm_start : 0; return 0; } static const struct seq_operations proc_pid_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_map }; static int maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_maps_op); } const struct file_operations proc_maps_operations = { .open = maps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; /* * Proportional Set Size(PSS): my share of RSS. * * PSS of a process is the count of pages it has in memory, where each * page is divided by the number of processes sharing it. So if a * process has 1000 pages all to itself, and 1000 shared with one other * process, its PSS will be 1500. * * To keep (accumulated) division errors low, we adopt a 64bit * fixed-point pss counter to minimize division errors. So (pss >> * PSS_SHIFT) would be the real byte count. * * A shift of 12 before division means (assuming 4K page size): * - 1M 3-user-pages add up to 8KB errors; * - supports mapcount up to 2^24, or 16M; * - supports PSS up to 2^52 bytes, or 4PB. */ #define PSS_SHIFT 12 #ifdef CONFIG_PROC_PAGE_MONITOR struct mem_size_stats { struct vm_area_struct *vma; unsigned long resident; unsigned long shared_clean; unsigned long shared_dirty; unsigned long private_clean; unsigned long private_dirty; unsigned long referenced; unsigned long anonymous; unsigned long anonymous_thp; unsigned long swap; u64 pss; }; static void smaps_pte_entry(pte_t ptent, unsigned long addr, unsigned long ptent_size, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = mss->vma; struct page *page; int mapcount; if (is_swap_pte(ptent)) { mss->swap += ptent_size; return; } if (!pte_present(ptent)) return; page = vm_normal_page(vma, addr, ptent); if (!page) return; if (PageAnon(page)) mss->anonymous += ptent_size; mss->resident += ptent_size; /* Accumulate the size in pages that have been accessed. */ if (pte_young(ptent) || PageReferenced(page)) mss->referenced += ptent_size; mapcount = page_mapcount(page); if (mapcount >= 2) { if (pte_dirty(ptent) || PageDirty(page)) mss->shared_dirty += ptent_size; else mss->shared_clean += ptent_size; mss->pss += (ptent_size << PSS_SHIFT) / mapcount; } else { if (pte_dirty(ptent) || PageDirty(page)) mss->private_dirty += ptent_size; else mss->private_clean += ptent_size; mss->pss += (ptent_size << PSS_SHIFT); } } static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = mss->vma; pte_t *pte; spinlock_t *ptl; spin_lock(&walk->mm->page_table_lock); if (pmd_trans_huge(*pmd)) { if (pmd_trans_splitting(*pmd)) { spin_unlock(&walk->mm->page_table_lock); wait_split_huge_page(vma->anon_vma, pmd); } else { smaps_pte_entry(*(pte_t *)pmd, addr, HPAGE_PMD_SIZE, walk); spin_unlock(&walk->mm->page_table_lock); mss->anonymous_thp += HPAGE_PMD_SIZE; return 0; } } else { spin_unlock(&walk->mm->page_table_lock); } /* * The mmap_sem held all the way back in m_start() is what * keeps khugepaged out of here and from collapsing things * in here. */ pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) smaps_pte_entry(*pte, addr, PAGE_SIZE, walk); pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } static int show_smap(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct task_struct *task = priv->task; struct vm_area_struct *vma = v; struct mem_size_stats mss; struct mm_walk smaps_walk = { .pmd_entry = smaps_pte_range, .mm = vma->vm_mm, .private = &mss, }; memset(&mss, 0, sizeof mss); mss.vma = vma; /* mmap_sem is held in m_start */ if (vma->vm_mm && !is_vm_hugetlb_page(vma)) walk_page_range(vma->vm_start, vma->vm_end, &smaps_walk); show_map_vma(m, vma); seq_printf(m, "Size: %8lu kB\n" "Rss: %8lu kB\n" "Pss: %8lu kB\n" "Shared_Clean: %8lu kB\n" "Shared_Dirty: %8lu kB\n" "Private_Clean: %8lu kB\n" "Private_Dirty: %8lu kB\n" "Referenced: %8lu kB\n" "Anonymous: %8lu kB\n" "AnonHugePages: %8lu kB\n" "Swap: %8lu kB\n" "KernelPageSize: %8lu kB\n" "MMUPageSize: %8lu kB\n" "Locked: %8lu kB\n", (vma->vm_end - vma->vm_start) >> 10, mss.resident >> 10, (unsigned long)(mss.pss >> (10 + PSS_SHIFT)), mss.shared_clean >> 10, mss.shared_dirty >> 10, mss.private_clean >> 10, mss.private_dirty >> 10, mss.referenced >> 10, mss.anonymous >> 10, mss.anonymous_thp >> 10, mss.swap >> 10, vma_kernel_pagesize(vma) >> 10, vma_mmu_pagesize(vma) >> 10, (vma->vm_flags & VM_LOCKED) ? (unsigned long)(mss.pss >> (10 + PSS_SHIFT)) : 0); if (m->count < m->size) /* vma is copied successfully */ m->version = (vma != get_gate_vma(task->mm)) ? vma->vm_start : 0; return 0; } static const struct seq_operations proc_pid_smaps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_smap }; static int smaps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_smaps_op); } const struct file_operations proc_smaps_operations = { .open = smaps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->private; pte_t *pte, ptent; spinlock_t *ptl; struct page *page; split_huge_page_pmd(walk->mm, pmd); pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) { ptent = *pte; if (!pte_present(ptent)) continue; page = vm_normal_page(vma, addr, ptent); if (!page) continue; /* Clear accessed and referenced bits. */ ptep_test_and_clear_young(vma, addr, pte); ClearPageReferenced(page); } pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } #define CLEAR_REFS_ALL 1 #define CLEAR_REFS_ANON 2 #define CLEAR_REFS_MAPPED 3 static ssize_t clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; long type; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; if (strict_strtol(strstrip(buffer), 10, &type)) return -EINVAL; if (type < CLEAR_REFS_ALL || type > CLEAR_REFS_MAPPED) return -EINVAL; task = get_proc_task(file->f_path.dentry->d_inode); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .mm = mm, }; down_read(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) { clear_refs_walk.private = vma; if (is_vm_hugetlb_page(vma)) continue; /* * Writing 1 to /proc/pid/clear_refs affects all pages. * * Writing 2 to /proc/pid/clear_refs only affects * Anonymous pages. * * Writing 3 to /proc/pid/clear_refs only affects file * mapped pages. */ if (type == CLEAR_REFS_ANON && vma->vm_file) continue; if (type == CLEAR_REFS_MAPPED && !vma->vm_file) continue; walk_page_range(vma->vm_start, vma->vm_end, &clear_refs_walk); } flush_tlb_mm(mm); up_read(&mm->mmap_sem); mmput(mm); } put_task_struct(task); return count; } const struct file_operations proc_clear_refs_operations = { .write = clear_refs_write, .llseek = noop_llseek, }; struct pagemapread { int pos, len; u64 *buffer; }; #define PM_ENTRY_BYTES sizeof(u64) #define PM_STATUS_BITS 3 #define PM_STATUS_OFFSET (64 - PM_STATUS_BITS) #define PM_STATUS_MASK (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET) #define PM_STATUS(nr) (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK) #define PM_PSHIFT_BITS 6 #define PM_PSHIFT_OFFSET (PM_STATUS_OFFSET - PM_PSHIFT_BITS) #define PM_PSHIFT_MASK (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET) #define PM_PSHIFT(x) (((u64) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK) #define PM_PFRAME_MASK ((1LL << PM_PSHIFT_OFFSET) - 1) #define PM_PFRAME(x) ((x) & PM_PFRAME_MASK) #define PM_PRESENT PM_STATUS(4LL) #define PM_SWAP PM_STATUS(2LL) #define PM_NOT_PRESENT PM_PSHIFT(PAGE_SHIFT) #define PM_END_OF_BUFFER 1 static int add_to_pagemap(unsigned long addr, u64 pfn, struct pagemapread *pm) { pm->buffer[pm->pos++] = pfn; if (pm->pos >= pm->len) return PM_END_OF_BUFFER; return 0; } static int pagemap_pte_hole(unsigned long start, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; unsigned long addr; int err = 0; for (addr = start; addr < end; addr += PAGE_SIZE) { err = add_to_pagemap(addr, PM_NOT_PRESENT, pm); if (err) break; } return err; } static u64 swap_pte_to_pagemap_entry(pte_t pte) { swp_entry_t e = pte_to_swp_entry(pte); return swp_type(e) | (swp_offset(e) << MAX_SWAPFILES_SHIFT); } static u64 pte_to_pagemap_entry(pte_t pte) { u64 pme = 0; if (is_swap_pte(pte)) pme = PM_PFRAME(swap_pte_to_pagemap_entry(pte)) | PM_PSHIFT(PAGE_SHIFT) | PM_SWAP; else if (pte_present(pte)) pme = PM_PFRAME(pte_pfn(pte)) | PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT; return pme; } static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma; struct pagemapread *pm = walk->private; pte_t *pte; int err = 0; split_huge_page_pmd(walk->mm, pmd); /* find the first VMA at or above 'addr' */ vma = find_vma(walk->mm, addr); for (; addr != end; addr += PAGE_SIZE) { u64 pfn = PM_NOT_PRESENT; /* check to see if we've left 'vma' behind * and need a new, higher one */ if (vma && (addr >= vma->vm_end)) vma = find_vma(walk->mm, addr); /* check that 'vma' actually covers this address, * and that it isn't a huge page vma */ if (vma && (vma->vm_start <= addr) && !is_vm_hugetlb_page(vma)) { pte = pte_offset_map(pmd, addr); pfn = pte_to_pagemap_entry(*pte); /* unmap before userspace copy */ pte_unmap(pte); } err = add_to_pagemap(addr, pfn, pm); if (err) return err; } cond_resched(); return err; } #ifdef CONFIG_HUGETLB_PAGE static u64 huge_pte_to_pagemap_entry(pte_t pte, int offset) { u64 pme = 0; if (pte_present(pte)) pme = PM_PFRAME(pte_pfn(pte) + offset) | PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT; return pme; } /* This function walks within one hugetlb entry in the single call */ static int pagemap_hugetlb_range(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; int err = 0; u64 pfn; for (; addr != end; addr += PAGE_SIZE) { int offset = (addr & ~hmask) >> PAGE_SHIFT; pfn = huge_pte_to_pagemap_entry(*pte, offset); err = add_to_pagemap(addr, pfn, pm); if (err) return err; } cond_resched(); return err; } #endif /* HUGETLB_PAGE */ /* * /proc/pid/pagemap - an array mapping virtual pages to pfns * * For each page in the address space, this file contains one 64-bit entry * consisting of the following: * * Bits 0-55 page frame number (PFN) if present * Bits 0-4 swap type if swapped * Bits 5-55 swap offset if swapped * Bits 55-60 page shift (page size = 1<<page shift) * Bit 61 reserved for future use * Bit 62 page swapped * Bit 63 page present * * If the page is not present but in swap, then the PFN contains an * encoding of the swap file number and the page's offset into the * swap. Unmapped pages return a null PFN. This allows determining * precisely which pages are mapped (or in swap) and comparing mapped * pages between processes. * * Efficient users of this interface will use /proc/pid/maps to * determine which areas of memory are actually mapped and llseek to * skip over unmapped regions. */ #define PAGEMAP_WALK_SIZE (PMD_SIZE) #define PAGEMAP_WALK_MASK (PMD_MASK) static ssize_t pagemap_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode); struct mm_struct *mm; struct pagemapread pm; int ret = -ESRCH; struct mm_walk pagemap_walk = {}; unsigned long src; unsigned long svpfn; unsigned long start_vaddr; unsigned long end_vaddr; int copied = 0; if (!task) goto out; mm = mm_for_maps(task); ret = PTR_ERR(mm); if (!mm || IS_ERR(mm)) goto out_task; ret = -EINVAL; /* file position must be aligned */ if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES)) goto out_task; ret = 0; if (!count) goto out_task; pm.len = PM_ENTRY_BYTES * (PAGEMAP_WALK_SIZE >> PAGE_SHIFT); pm.buffer = kmalloc(pm.len, GFP_TEMPORARY); ret = -ENOMEM; if (!pm.buffer) goto out_mm; pagemap_walk.pmd_entry = pagemap_pte_range; pagemap_walk.pte_hole = pagemap_pte_hole; #ifdef CONFIG_HUGETLB_PAGE pagemap_walk.hugetlb_entry = pagemap_hugetlb_range; #endif pagemap_walk.mm = mm; pagemap_walk.private = &pm; src = *ppos; svpfn = src / PM_ENTRY_BYTES; start_vaddr = svpfn << PAGE_SHIFT; end_vaddr = TASK_SIZE_OF(task); /* watch out for wraparound */ if (svpfn > TASK_SIZE_OF(task) >> PAGE_SHIFT) start_vaddr = end_vaddr; /* * The odds are that this will stop walking way * before end_vaddr, because the length of the * user buffer is tracked in "pm", and the walk * will stop when we hit the end of the buffer. */ ret = 0; while (count && (start_vaddr < end_vaddr)) { int len; unsigned long end; pm.pos = 0; end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK; /* overflow ? */ if (end < start_vaddr || end > end_vaddr) end = end_vaddr; down_read(&mm->mmap_sem); ret = walk_page_range(start_vaddr, end, &pagemap_walk); up_read(&mm->mmap_sem); start_vaddr = end; len = min(count, PM_ENTRY_BYTES * pm.pos); if (copy_to_user(buf, pm.buffer, len)) { ret = -EFAULT; goto out_free; } copied += len; buf += len; count -= len; } *ppos += copied; if (!ret || ret == PM_END_OF_BUFFER) ret = copied; out_free: kfree(pm.buffer); out_mm: mmput(mm); out_task: put_task_struct(task); out: return ret; } const struct file_operations proc_pagemap_operations = { .llseek = mem_lseek, /* borrow this */ .read = pagemap_read, }; #endif /* CONFIG_PROC_PAGE_MONITOR */ #ifdef CONFIG_NUMA extern int show_numa_map(struct seq_file *m, void *v); static const struct seq_operations proc_pid_numa_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_numa_map, }; static int numa_maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_numa_maps_op); } const struct file_operations proc_numa_maps_operations = { .open = numa_maps_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; #endif
static void m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); }
static void m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; if (!IS_ERR(vma)) vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); }
{'added': [(185, '\tif (!IS_ERR(vma))'), (186, '\t\tvma_stop(priv, vma);')], 'deleted': [(185, '\tvma_stop(priv, vma);')]}
2
1
648
3,971
https://github.com/torvalds/linux
CVE-2011-3637
['CWE-476']
card-cac1.c
cac_cac1_get_certificate
/* * card-cac1.c: Support for legacy CAC-1 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/sha.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #include "card-cac-common.h" /* * CAC hardware and APDU constants */ #define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */ /* * OLD cac read certificate, only use with CAC-1 card. */ static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len, next_len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); next_len = MIN(left, 100); for (; left > 0; left -= len, out_ptr += len) { len = next_len; apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } next_len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path=%s, path->value=%s path->type=%d (%x)", sc_print_path(in_path), sc_dump_hex(in_path->value, in_path->len), in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, iso7816_select_file expects paths to keys to have specific * formats. There is no override. We have to add some bytes to the * path to make it happy. * We only need to do this for private keys. */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { path += 2; pathlen -= 2; } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; apdu.p2 = 0x00; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { u8 data[2]; sc_apdu_t apdu; /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, CAC_INS_GET_CERTIFICATE, 0x00, 0x00); apdu.le = 0x02; apdu.resplen = 2; apdu.resp = data; r = sc_transmit_apdu(card, &apdu); /* SW1 = 0x63 means more data in CAC1 */ if (r == SC_SUCCESS && apdu.sw1 != 0x63) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = get_cac_label(i); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s)", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = sizeof(buf); r = cac_cac1_get_certificate(card, &val, &val_len); if (r >= 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac1(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_I; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac1_drv = { "Common Access Card (CAC 1)", "cac1", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { /* Inherit most of the things from the CAC driver */ struct sc_card_driver *cac_drv = sc_get_cac_driver(); cac_ops = *cac_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.read_binary = cac_read_binary; return &cac1_drv; } struct sc_card_driver * sc_get_cac1_driver(void) { return sc_get_driver(); }
/* * card-cac1.c: Support for legacy CAC-1 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/sha.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #include "card-cac-common.h" /* * CAC hardware and APDU constants */ #define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */ /* * OLD cac read certificate, only use with CAC-1 card. */ static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); len = MIN(left, 100); for (; left > 0;) { /* Increments for readability in the end of the function */ apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } /* Adjust the lengths */ left -= len; out_ptr += len; len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len = 0; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path=%s, path->value=%s path->type=%d (%x)", sc_print_path(in_path), sc_dump_hex(in_path->value, in_path->len), in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, iso7816_select_file expects paths to keys to have specific * formats. There is no override. We have to add some bytes to the * path to make it happy. * We only need to do this for private keys. */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { path += 2; pathlen -= 2; } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; apdu.p2 = 0x00; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { u8 data[2]; sc_apdu_t apdu; /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, CAC_INS_GET_CERTIFICATE, 0x00, 0x00); apdu.le = 0x02; apdu.resplen = 2; apdu.resp = data; r = sc_transmit_apdu(card, &apdu); /* SW1 = 0x63 means more data in CAC1 */ if (r == SC_SUCCESS && apdu.sw1 != 0x63) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = get_cac_label(i); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s)", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = sizeof(buf); r = cac_cac1_get_certificate(card, &val, &val_len); if (r >= 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac1(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_I; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac1_drv = { "Common Access Card (CAC 1)", "cac1", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { /* Inherit most of the things from the CAC driver */ struct sc_card_driver *cac_drv = sc_get_cac_driver(); cac_ops = *cac_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.read_binary = cac_read_binary; return &cac1_drv; } struct sc_card_driver * sc_get_cac1_driver(void) { return sc_get_driver(); }
static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len, next_len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); next_len = MIN(left, 100); for (; left > 0; left -= len, out_ptr += len) { len = next_len; apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } next_len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); }
static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); len = MIN(left, 100); for (; left > 0;) { /* Increments for readability in the end of the function */ apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } /* Adjust the lengths */ left -= len; out_ptr += len; len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); }
{'added': [(72, '\tsize_t len;'), (80, '\tlen = MIN(left, 100);'), (81, '\tfor (; left > 0;) { /* Increments for readability in the end of the function */'), (100, '\t\t/* Adjust the lengths */'), (101, '\t\tleft -= len;'), (102, '\t\tout_ptr += len;'), (103, '\t\tlen = MIN(left, apdu.sw2);'), (133, '\tsize_t val_len = 0;')], 'deleted': [(72, '\tsize_t len, next_len;'), (80, '\tnext_len = MIN(left, 100);'), (81, '\tfor (; left > 0; left -= len, out_ptr += len) {'), (82, '\t\tlen = next_len;'), (101, '\t\tnext_len = MIN(left, apdu.sw2);'), (131, '\tsize_t val_len;')]}
8
6
384
2,384
https://github.com/OpenSC/OpenSC
CVE-2019-19481
['CWE-119']
card-cac1.c
cac_read_binary
/* * card-cac1.c: Support for legacy CAC-1 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/sha.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #include "card-cac-common.h" /* * CAC hardware and APDU constants */ #define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */ /* * OLD cac read certificate, only use with CAC-1 card. */ static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len, next_len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); next_len = MIN(left, 100); for (; left > 0; left -= len, out_ptr += len) { len = next_len; apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } next_len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path=%s, path->value=%s path->type=%d (%x)", sc_print_path(in_path), sc_dump_hex(in_path->value, in_path->len), in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, iso7816_select_file expects paths to keys to have specific * formats. There is no override. We have to add some bytes to the * path to make it happy. * We only need to do this for private keys. */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { path += 2; pathlen -= 2; } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; apdu.p2 = 0x00; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { u8 data[2]; sc_apdu_t apdu; /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, CAC_INS_GET_CERTIFICATE, 0x00, 0x00); apdu.le = 0x02; apdu.resplen = 2; apdu.resp = data; r = sc_transmit_apdu(card, &apdu); /* SW1 = 0x63 means more data in CAC1 */ if (r == SC_SUCCESS && apdu.sw1 != 0x63) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = get_cac_label(i); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s)", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = sizeof(buf); r = cac_cac1_get_certificate(card, &val, &val_len); if (r >= 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac1(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_I; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac1_drv = { "Common Access Card (CAC 1)", "cac1", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { /* Inherit most of the things from the CAC driver */ struct sc_card_driver *cac_drv = sc_get_cac_driver(); cac_ops = *cac_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.read_binary = cac_read_binary; return &cac1_drv; } struct sc_card_driver * sc_get_cac1_driver(void) { return sc_get_driver(); }
/* * card-cac1.c: Support for legacy CAC-1 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/sha.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #include "card-cac-common.h" /* * CAC hardware and APDU constants */ #define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */ /* * OLD cac read certificate, only use with CAC-1 card. */ static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); len = MIN(left, 100); for (; left > 0;) { /* Increments for readability in the end of the function */ apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } /* Adjust the lengths */ left -= len; out_ptr += len; len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len = 0; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path=%s, path->value=%s path->type=%d (%x)", sc_print_path(in_path), sc_dump_hex(in_path->value, in_path->len), in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, iso7816_select_file expects paths to keys to have specific * formats. There is no override. We have to add some bytes to the * path to make it happy. * We only need to do this for private keys. */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { path += 2; pathlen -= 2; } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; apdu.p2 = 0x00; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { u8 data[2]; sc_apdu_t apdu; /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, CAC_INS_GET_CERTIFICATE, 0x00, 0x00); apdu.le = 0x02; apdu.resplen = 2; apdu.resp = data; r = sc_transmit_apdu(card, &apdu); /* SW1 = 0x63 means more data in CAC1 */ if (r == SC_SUCCESS && apdu.sw1 != 0x63) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = get_cac_label(i); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s)", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = sizeof(buf); r = cac_cac1_get_certificate(card, &val, &val_len); if (r >= 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac1(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_I; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac1_drv = { "Common Access Card (CAC 1)", "cac1", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { /* Inherit most of the things from the CAC driver */ struct sc_card_driver *cac_drv = sc_get_cac_driver(); cac_ops = *cac_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.read_binary = cac_read_binary; return &cac1_drv; } struct sc_card_driver * sc_get_cac1_driver(void) { return sc_get_driver(); }
static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); }
static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *val = NULL; u8 *cert_ptr; size_t val_len = 0; size_t len, cert_len; u8 cert_type; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_log(card->ctx, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); LOG_FUNC_RETURN(card->ctx, len); } sc_log(card->ctx, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; r = cac_cac1_get_certificate(card, &val, &val_len); if (r < 0) goto done; if (val_len < 1) { r = SC_ERROR_INVALID_DATA; goto done; } cert_type = val[0]; cert_ptr = val + 1; cert_len = val_len - 1; /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); if (len && priv->cache_buf) memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (val) free(val); LOG_FUNC_RETURN(card->ctx, r); }
{'added': [(72, '\tsize_t len;'), (80, '\tlen = MIN(left, 100);'), (81, '\tfor (; left > 0;) { /* Increments for readability in the end of the function */'), (100, '\t\t/* Adjust the lengths */'), (101, '\t\tleft -= len;'), (102, '\t\tout_ptr += len;'), (103, '\t\tlen = MIN(left, apdu.sw2);'), (133, '\tsize_t val_len = 0;')], 'deleted': [(72, '\tsize_t len, next_len;'), (80, '\tnext_len = MIN(left, 100);'), (81, '\tfor (; left > 0; left -= len, out_ptr += len) {'), (82, '\t\tlen = next_len;'), (101, '\t\tnext_len = MIN(left, apdu.sw2);'), (131, '\tsize_t val_len;')]}
8
6
384
2,384
https://github.com/OpenSC/OpenSC
CVE-2019-19481
['CWE-119']
xwd-loader.c
load_header
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2018-2022 Hans Petter Jansson * * This file is part of Chafa, a program that turns images into character art. * * Chafa is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Chafa 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 General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Chafa. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <assert.h> #include <errno.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <chafa.h> #include "xwd-loader.h" #define DEBUG(x) typedef struct { guint32 header_size; /* Size of the header in bytes */ guint32 file_version; /* X11WD file version (always 07h) */ guint32 pixmap_format; /* Pixmap format */ guint32 pixmap_depth; /* Pixmap depth in pixels */ guint32 pixmap_width; /* Pixmap width in pixels */ guint32 pixmap_height; /* Pixmap height in pixels */ guint32 x_offset; /* Bitmap X offset */ guint32 byte_order; /* Byte order of image data */ guint32 bitmap_unit; /* Bitmap base data size */ guint32 bitmap_bit_order; /* Bit-order of image data */ guint32 bitmap_pad; /* Bitmap scan-line pad*/ guint32 bits_per_pixel; /* Bits per pixel */ guint32 bytes_per_line; /* Bytes per scan-line */ guint32 visual_class; /* Class of the image */ guint32 red_mask; /* Red mask */ guint32 green_mask; /* Green mask */ guint32 blue_mask; /* Blue mask */ guint32 bits_per_rgb; /* Size of each color mask in bits */ guint32 n_colors; /* Number of colors in image */ guint32 color_map_entries; /* Number of entries in color map */ guint32 window_width; /* Window width */ guint32 window_height; /* Window height */ gint32 window_x; /* Window upper left X coordinate */ gint32 window_y; /* Window upper left Y coordinate */ guint32 window_border_width; /* Window border width */ } XwdHeader; typedef struct { guint32 pixel; guint16 red; guint16 green; guint16 blue; guint8 flags; guint8 pad; } XwdColor; struct XwdLoader { FileMapping *mapping; gconstpointer file_data; gconstpointer image_data; gsize file_data_len; XwdHeader header; }; DEBUG ( static void dump_header (XwdHeader *header) { g_printerr ("Header size: %u\n" "File version: %u\n" "Pixmap format: %u\n" "Pixmap depth: %u\n" "Pixmap width: %u\n" "Pixmap height: %u\n" "X offset: %u\n" "Byte order: %u\n" "Bitmap unit: %u\n" "Bitmap bit order: %u\n" "Bitmap pad: %u\n" "Bits per pixel: %u\n" "Bytes per line: %u\n" "Visual class: %u\n" "Red mask: %u\n" "Green mask: %u\n" "Blue mask: %u\n" "Bits per RGB: %u\n" "Number of colors: %u\n" "Color map entries: %u\n" "Window width: %u\n" "Window height: %u\n" "Window X: %d\n" "Window Y: %d\n" "Window border width: %u\n---\n", header->header_size, header->file_version, header->pixmap_format, header->pixmap_depth, header->pixmap_width, header->pixmap_height, header->x_offset, header->byte_order, header->bitmap_unit, header->bitmap_bit_order, header->bitmap_pad, header->bits_per_pixel, header->bytes_per_line, header->visual_class, header->red_mask, header->green_mask, header->blue_mask, header->bits_per_rgb, header->n_colors, header->color_map_entries, header->window_width, header->window_height, header->window_x, header->window_y, header->window_border_width); } ) static ChafaPixelType compute_pixel_type (XwdLoader *loader) { XwdHeader *h = &loader->header; if (h->bits_per_pixel == 24) { if (h->byte_order == 0) return CHAFA_PIXEL_BGR8; else return CHAFA_PIXEL_RGB8; } if (h->bits_per_pixel == 32) { if (h->byte_order == 0) return CHAFA_PIXEL_BGRA8_PREMULTIPLIED; else return CHAFA_PIXEL_ARGB8_PREMULTIPLIED; } return CHAFA_PIXEL_MAX; } #define ASSERT_HEADER(x) if (!(x)) return FALSE static gboolean load_header (XwdLoader *loader) // gconstpointer in, gsize in_max_len, XwdHeader *header_out) { XwdHeader *h = &loader->header; XwdHeader in; const guint32 *p = (const guint32 *) &in; if (!file_mapping_taste (loader->mapping, &in, 0, sizeof (in))) return FALSE; h->header_size = g_ntohl (*(p++)); h->file_version = g_ntohl (*(p++)); h->pixmap_format = g_ntohl (*(p++)); h->pixmap_depth = g_ntohl (*(p++)); h->pixmap_width = g_ntohl (*(p++)); h->pixmap_height = g_ntohl (*(p++)); h->x_offset = g_ntohl (*(p++)); h->byte_order = g_ntohl (*(p++)); h->bitmap_unit = g_ntohl (*(p++)); h->bitmap_bit_order = g_ntohl (*(p++)); h->bitmap_pad = g_ntohl (*(p++)); h->bits_per_pixel = g_ntohl (*(p++)); h->bytes_per_line = g_ntohl (*(p++)); h->visual_class = g_ntohl (*(p++)); h->red_mask = g_ntohl (*(p++)); h->green_mask = g_ntohl (*(p++)); h->blue_mask = g_ntohl (*(p++)); h->bits_per_rgb = g_ntohl (*(p++)); h->color_map_entries = g_ntohl (*(p++)); h->n_colors = g_ntohl (*(p++)); h->window_width = g_ntohl (*(p++)); h->window_height = g_ntohl (*(p++)); h->window_x = g_ntohl (*(p++)); h->window_y = g_ntohl (*(p++)); h->window_border_width = g_ntohl (*(p++)); /* Only support the most common/useful subset of XWD files out there; * namely, that corresponding to screen dumps from modern X.Org servers. */ ASSERT_HEADER (h->header_size >= sizeof (XwdHeader)); ASSERT_HEADER (h->file_version == 7); ASSERT_HEADER (h->pixmap_depth == 24); /* Xvfb sets bits_per_rgb to 8, but 'convert' uses 24 for the same image data. One * of them is likely misunderstanding. Let's be lenient and accept either. */ ASSERT_HEADER (h->bits_per_rgb == 8 || h->bits_per_rgb == 24); ASSERT_HEADER (h->bytes_per_line >= h->pixmap_width * (h->bits_per_pixel / 8)); ASSERT_HEADER (compute_pixel_type (loader) < CHAFA_PIXEL_MAX); loader->file_data = file_mapping_get_data (loader->mapping, &loader->file_data_len); if (!loader->file_data) return FALSE; ASSERT_HEADER (loader->file_data_len >= h->header_size + h->n_colors * sizeof (XwdColor) + h->pixmap_height * h->bytes_per_line); loader->image_data = (const guint8 *) loader->file_data + h->header_size + h->n_colors * sizeof (XwdColor); return TRUE; } static XwdLoader * xwd_loader_new (void) { return g_new0 (XwdLoader, 1); } XwdLoader * xwd_loader_new_from_mapping (FileMapping *mapping) { XwdLoader *loader = NULL; gboolean success = FALSE; g_return_val_if_fail (mapping != NULL, NULL); loader = xwd_loader_new (); loader->mapping = mapping; if (!load_header (loader)) { g_free (loader); return NULL; } DEBUG (dump_header (&loader->header)); if (loader->header.pixmap_width < 1 || loader->header.pixmap_width >= (1 << 28) || loader->header.pixmap_height < 1 || loader->header.pixmap_height >= (1 << 28) || (loader->header.pixmap_width * (guint64) loader->header.pixmap_height >= (1 << 29))) goto out; success = TRUE; out: if (!success) { g_free (loader); loader = NULL; } return loader; } void xwd_loader_destroy (XwdLoader *loader) { if (loader->mapping) file_mapping_destroy (loader->mapping); g_free (loader); } gboolean xwd_loader_get_is_animation (G_GNUC_UNUSED XwdLoader *loader) { return FALSE; } gconstpointer xwd_loader_get_frame_data (XwdLoader *loader, ChafaPixelType *pixel_type_out, gint *width_out, gint *height_out, gint *rowstride_out) { g_return_val_if_fail (loader != NULL, NULL); if (pixel_type_out) *pixel_type_out = compute_pixel_type (loader); if (width_out) *width_out = loader->header.pixmap_width; if (height_out) *height_out = loader->header.pixmap_height; if (rowstride_out) *rowstride_out = loader->header.bytes_per_line; return loader->image_data; } gint xwd_loader_get_frame_delay (G_GNUC_UNUSED XwdLoader *loader) { return 0; } void xwd_loader_goto_first_frame (G_GNUC_UNUSED XwdLoader *loader) { } gboolean xwd_loader_goto_next_frame (G_GNUC_UNUSED XwdLoader *loader) { return FALSE; }
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2018-2022 Hans Petter Jansson * * This file is part of Chafa, a program that turns images into character art. * * Chafa is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Chafa 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 General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Chafa. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <assert.h> #include <errno.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <chafa.h> #include "xwd-loader.h" #define DEBUG(x) typedef struct { guint32 header_size; /* Size of the header in bytes */ guint32 file_version; /* X11WD file version (always 07h) */ guint32 pixmap_format; /* Pixmap format */ guint32 pixmap_depth; /* Pixmap depth in pixels */ guint32 pixmap_width; /* Pixmap width in pixels */ guint32 pixmap_height; /* Pixmap height in pixels */ guint32 x_offset; /* Bitmap X offset */ guint32 byte_order; /* Byte order of image data */ guint32 bitmap_unit; /* Bitmap base data size */ guint32 bitmap_bit_order; /* Bit-order of image data */ guint32 bitmap_pad; /* Bitmap scan-line pad*/ guint32 bits_per_pixel; /* Bits per pixel */ guint32 bytes_per_line; /* Bytes per scan-line */ guint32 visual_class; /* Class of the image */ guint32 red_mask; /* Red mask */ guint32 green_mask; /* Green mask */ guint32 blue_mask; /* Blue mask */ guint32 bits_per_rgb; /* Size of each color mask in bits */ guint32 n_colors; /* Number of colors in image */ guint32 color_map_entries; /* Number of entries in color map */ guint32 window_width; /* Window width */ guint32 window_height; /* Window height */ gint32 window_x; /* Window upper left X coordinate */ gint32 window_y; /* Window upper left Y coordinate */ guint32 window_border_width; /* Window border width */ } XwdHeader; typedef struct { guint32 pixel; guint16 red; guint16 green; guint16 blue; guint8 flags; guint8 pad; } XwdColor; struct XwdLoader { FileMapping *mapping; gconstpointer file_data; gconstpointer image_data; gsize file_data_len; XwdHeader header; }; DEBUG ( static void dump_header (XwdHeader *header) { g_printerr ("Header size: %u\n" "File version: %u\n" "Pixmap format: %u\n" "Pixmap depth: %u\n" "Pixmap width: %u\n" "Pixmap height: %u\n" "X offset: %u\n" "Byte order: %u\n" "Bitmap unit: %u\n" "Bitmap bit order: %u\n" "Bitmap pad: %u\n" "Bits per pixel: %u\n" "Bytes per line: %u\n" "Visual class: %u\n" "Red mask: %u\n" "Green mask: %u\n" "Blue mask: %u\n" "Bits per RGB: %u\n" "Number of colors: %u\n" "Color map entries: %u\n" "Window width: %u\n" "Window height: %u\n" "Window X: %d\n" "Window Y: %d\n" "Window border width: %u\n---\n", header->header_size, header->file_version, header->pixmap_format, header->pixmap_depth, header->pixmap_width, header->pixmap_height, header->x_offset, header->byte_order, header->bitmap_unit, header->bitmap_bit_order, header->bitmap_pad, header->bits_per_pixel, header->bytes_per_line, header->visual_class, header->red_mask, header->green_mask, header->blue_mask, header->bits_per_rgb, header->n_colors, header->color_map_entries, header->window_width, header->window_height, header->window_x, header->window_y, header->window_border_width); } ) static ChafaPixelType compute_pixel_type (XwdLoader *loader) { XwdHeader *h = &loader->header; if (h->bits_per_pixel == 24) { if (h->byte_order == 0) return CHAFA_PIXEL_BGR8; else return CHAFA_PIXEL_RGB8; } if (h->bits_per_pixel == 32) { if (h->byte_order == 0) return CHAFA_PIXEL_BGRA8_PREMULTIPLIED; else return CHAFA_PIXEL_ARGB8_PREMULTIPLIED; } return CHAFA_PIXEL_MAX; } #define ASSERT_HEADER(x) if (!(x)) return FALSE #define UNPACK_FIELD_U32(dest, src, field) ((dest)->field = GUINT32_FROM_BE ((src)->field)) #define UNPACK_FIELD_S32(dest, src, field) ((dest)->field = GINT32_FROM_BE ((src)->field)) static gboolean load_header (XwdLoader *loader) { XwdHeader *h = &loader->header; XwdHeader in; const XwdHeader *inp; if (!file_mapping_taste (loader->mapping, &in, 0, sizeof (in))) return FALSE; inp = &in; UNPACK_FIELD_U32 (h, inp, header_size); UNPACK_FIELD_U32 (h, inp, file_version); UNPACK_FIELD_U32 (h, inp, pixmap_format); UNPACK_FIELD_U32 (h, inp, pixmap_depth); UNPACK_FIELD_U32 (h, inp, pixmap_width); UNPACK_FIELD_U32 (h, inp, pixmap_height); UNPACK_FIELD_U32 (h, inp, x_offset); UNPACK_FIELD_U32 (h, inp, byte_order); UNPACK_FIELD_U32 (h, inp, bitmap_unit); UNPACK_FIELD_U32 (h, inp, bitmap_bit_order); UNPACK_FIELD_U32 (h, inp, bitmap_pad); UNPACK_FIELD_U32 (h, inp, bits_per_pixel); UNPACK_FIELD_U32 (h, inp, bytes_per_line); UNPACK_FIELD_U32 (h, inp, visual_class); UNPACK_FIELD_U32 (h, inp, red_mask); UNPACK_FIELD_U32 (h, inp, green_mask); UNPACK_FIELD_U32 (h, inp, blue_mask); UNPACK_FIELD_U32 (h, inp, bits_per_rgb); UNPACK_FIELD_U32 (h, inp, color_map_entries); UNPACK_FIELD_U32 (h, inp, n_colors); UNPACK_FIELD_U32 (h, inp, window_width); UNPACK_FIELD_U32 (h, inp, window_height); UNPACK_FIELD_S32 (h, inp, window_x); UNPACK_FIELD_S32 (h, inp, window_y); UNPACK_FIELD_U32 (h, inp, window_border_width); /* Only support the most common/useful subset of XWD files out there; * namely, that corresponding to screen dumps from modern X.Org servers. * We could check visual_class == 5 too, but the other fields convey all * the info we need. */ ASSERT_HEADER (h->header_size >= sizeof (XwdHeader)); ASSERT_HEADER (h->header_size <= 65535); ASSERT_HEADER (h->file_version == 7); ASSERT_HEADER (h->pixmap_depth == 24); /* Should be zero for truecolor/directcolor. Cap it to prevent overflows. */ ASSERT_HEADER (h->color_map_entries <= 256); /* Xvfb sets bits_per_rgb to 8, but 'convert' uses 24 for the same image data. One * of them is likely misunderstanding. Let's be lenient and accept either. */ ASSERT_HEADER (h->bits_per_rgb == 8 || h->bits_per_rgb == 24); /* These are the pixel formats we allow. */ ASSERT_HEADER (h->bits_per_pixel == 24 || h->bits_per_pixel == 32); /* Enforce sane dimensions. */ ASSERT_HEADER (h->pixmap_width >= 1 && h->pixmap_width <= 65535); ASSERT_HEADER (h->pixmap_height >= 1 && h->pixmap_height <= 65535); /* Make sure rowstride can actually hold a row's worth of data but is not padded to * something ridiculous. */ ASSERT_HEADER (h->bytes_per_line >= h->pixmap_width * (h->bits_per_pixel / 8)); ASSERT_HEADER (h->bytes_per_line <= h->pixmap_width * (h->bits_per_pixel / 8) + 1024); /* Make sure the total allocation/map is not too big. */ ASSERT_HEADER (h->bytes_per_line * h->pixmap_height < (1UL << 31) - 65536 - 256 * 32); ASSERT_HEADER (compute_pixel_type (loader) < CHAFA_PIXEL_MAX); loader->file_data = file_mapping_get_data (loader->mapping, &loader->file_data_len); if (!loader->file_data) return FALSE; ASSERT_HEADER (loader->file_data_len >= h->header_size + h->color_map_entries * sizeof (XwdColor) + h->pixmap_height * (gsize) h->bytes_per_line); loader->image_data = (const guint8 *) loader->file_data + h->header_size + h->color_map_entries * sizeof (XwdColor); return TRUE; } static XwdLoader * xwd_loader_new (void) { return g_new0 (XwdLoader, 1); } XwdLoader * xwd_loader_new_from_mapping (FileMapping *mapping) { XwdLoader *loader = NULL; gboolean success = FALSE; g_return_val_if_fail (mapping != NULL, NULL); loader = xwd_loader_new (); loader->mapping = mapping; if (!load_header (loader)) { g_free (loader); return NULL; } DEBUG (dump_header (&loader->header)); if (loader->header.pixmap_width < 1 || loader->header.pixmap_width >= (1 << 28) || loader->header.pixmap_height < 1 || loader->header.pixmap_height >= (1 << 28) || (loader->header.pixmap_width * (guint64) loader->header.pixmap_height >= (1 << 29))) goto out; success = TRUE; out: if (!success) { g_free (loader); loader = NULL; } return loader; } void xwd_loader_destroy (XwdLoader *loader) { if (loader->mapping) file_mapping_destroy (loader->mapping); g_free (loader); } gboolean xwd_loader_get_is_animation (G_GNUC_UNUSED XwdLoader *loader) { return FALSE; } gconstpointer xwd_loader_get_frame_data (XwdLoader *loader, ChafaPixelType *pixel_type_out, gint *width_out, gint *height_out, gint *rowstride_out) { g_return_val_if_fail (loader != NULL, NULL); if (pixel_type_out) *pixel_type_out = compute_pixel_type (loader); if (width_out) *width_out = loader->header.pixmap_width; if (height_out) *height_out = loader->header.pixmap_height; if (rowstride_out) *rowstride_out = loader->header.bytes_per_line; return loader->image_data; } gint xwd_loader_get_frame_delay (G_GNUC_UNUSED XwdLoader *loader) { return 0; } void xwd_loader_goto_first_frame (G_GNUC_UNUSED XwdLoader *loader) { } gboolean xwd_loader_goto_next_frame (G_GNUC_UNUSED XwdLoader *loader) { return FALSE; }
load_header (XwdLoader *loader) // gconstpointer in, gsize in_max_len, XwdHeader *header_out) { XwdHeader *h = &loader->header; XwdHeader in; const guint32 *p = (const guint32 *) &in; if (!file_mapping_taste (loader->mapping, &in, 0, sizeof (in))) return FALSE; h->header_size = g_ntohl (*(p++)); h->file_version = g_ntohl (*(p++)); h->pixmap_format = g_ntohl (*(p++)); h->pixmap_depth = g_ntohl (*(p++)); h->pixmap_width = g_ntohl (*(p++)); h->pixmap_height = g_ntohl (*(p++)); h->x_offset = g_ntohl (*(p++)); h->byte_order = g_ntohl (*(p++)); h->bitmap_unit = g_ntohl (*(p++)); h->bitmap_bit_order = g_ntohl (*(p++)); h->bitmap_pad = g_ntohl (*(p++)); h->bits_per_pixel = g_ntohl (*(p++)); h->bytes_per_line = g_ntohl (*(p++)); h->visual_class = g_ntohl (*(p++)); h->red_mask = g_ntohl (*(p++)); h->green_mask = g_ntohl (*(p++)); h->blue_mask = g_ntohl (*(p++)); h->bits_per_rgb = g_ntohl (*(p++)); h->color_map_entries = g_ntohl (*(p++)); h->n_colors = g_ntohl (*(p++)); h->window_width = g_ntohl (*(p++)); h->window_height = g_ntohl (*(p++)); h->window_x = g_ntohl (*(p++)); h->window_y = g_ntohl (*(p++)); h->window_border_width = g_ntohl (*(p++)); /* Only support the most common/useful subset of XWD files out there; * namely, that corresponding to screen dumps from modern X.Org servers. */ ASSERT_HEADER (h->header_size >= sizeof (XwdHeader)); ASSERT_HEADER (h->file_version == 7); ASSERT_HEADER (h->pixmap_depth == 24); /* Xvfb sets bits_per_rgb to 8, but 'convert' uses 24 for the same image data. One * of them is likely misunderstanding. Let's be lenient and accept either. */ ASSERT_HEADER (h->bits_per_rgb == 8 || h->bits_per_rgb == 24); ASSERT_HEADER (h->bytes_per_line >= h->pixmap_width * (h->bits_per_pixel / 8)); ASSERT_HEADER (compute_pixel_type (loader) < CHAFA_PIXEL_MAX); loader->file_data = file_mapping_get_data (loader->mapping, &loader->file_data_len); if (!loader->file_data) return FALSE; ASSERT_HEADER (loader->file_data_len >= h->header_size + h->n_colors * sizeof (XwdColor) + h->pixmap_height * h->bytes_per_line); loader->image_data = (const guint8 *) loader->file_data + h->header_size + h->n_colors * sizeof (XwdColor); return TRUE; }
load_header (XwdLoader *loader) { XwdHeader *h = &loader->header; XwdHeader in; const XwdHeader *inp; if (!file_mapping_taste (loader->mapping, &in, 0, sizeof (in))) return FALSE; inp = &in; UNPACK_FIELD_U32 (h, inp, header_size); UNPACK_FIELD_U32 (h, inp, file_version); UNPACK_FIELD_U32 (h, inp, pixmap_format); UNPACK_FIELD_U32 (h, inp, pixmap_depth); UNPACK_FIELD_U32 (h, inp, pixmap_width); UNPACK_FIELD_U32 (h, inp, pixmap_height); UNPACK_FIELD_U32 (h, inp, x_offset); UNPACK_FIELD_U32 (h, inp, byte_order); UNPACK_FIELD_U32 (h, inp, bitmap_unit); UNPACK_FIELD_U32 (h, inp, bitmap_bit_order); UNPACK_FIELD_U32 (h, inp, bitmap_pad); UNPACK_FIELD_U32 (h, inp, bits_per_pixel); UNPACK_FIELD_U32 (h, inp, bytes_per_line); UNPACK_FIELD_U32 (h, inp, visual_class); UNPACK_FIELD_U32 (h, inp, red_mask); UNPACK_FIELD_U32 (h, inp, green_mask); UNPACK_FIELD_U32 (h, inp, blue_mask); UNPACK_FIELD_U32 (h, inp, bits_per_rgb); UNPACK_FIELD_U32 (h, inp, color_map_entries); UNPACK_FIELD_U32 (h, inp, n_colors); UNPACK_FIELD_U32 (h, inp, window_width); UNPACK_FIELD_U32 (h, inp, window_height); UNPACK_FIELD_S32 (h, inp, window_x); UNPACK_FIELD_S32 (h, inp, window_y); UNPACK_FIELD_U32 (h, inp, window_border_width); /* Only support the most common/useful subset of XWD files out there; * namely, that corresponding to screen dumps from modern X.Org servers. * We could check visual_class == 5 too, but the other fields convey all * the info we need. */ ASSERT_HEADER (h->header_size >= sizeof (XwdHeader)); ASSERT_HEADER (h->header_size <= 65535); ASSERT_HEADER (h->file_version == 7); ASSERT_HEADER (h->pixmap_depth == 24); /* Should be zero for truecolor/directcolor. Cap it to prevent overflows. */ ASSERT_HEADER (h->color_map_entries <= 256); /* Xvfb sets bits_per_rgb to 8, but 'convert' uses 24 for the same image data. One * of them is likely misunderstanding. Let's be lenient and accept either. */ ASSERT_HEADER (h->bits_per_rgb == 8 || h->bits_per_rgb == 24); /* These are the pixel formats we allow. */ ASSERT_HEADER (h->bits_per_pixel == 24 || h->bits_per_pixel == 32); /* Enforce sane dimensions. */ ASSERT_HEADER (h->pixmap_width >= 1 && h->pixmap_width <= 65535); ASSERT_HEADER (h->pixmap_height >= 1 && h->pixmap_height <= 65535); /* Make sure rowstride can actually hold a row's worth of data but is not padded to * something ridiculous. */ ASSERT_HEADER (h->bytes_per_line >= h->pixmap_width * (h->bits_per_pixel / 8)); ASSERT_HEADER (h->bytes_per_line <= h->pixmap_width * (h->bits_per_pixel / 8) + 1024); /* Make sure the total allocation/map is not too big. */ ASSERT_HEADER (h->bytes_per_line * h->pixmap_height < (1UL << 31) - 65536 - 256 * 32); ASSERT_HEADER (compute_pixel_type (loader) < CHAFA_PIXEL_MAX); loader->file_data = file_mapping_get_data (loader->mapping, &loader->file_data_len); if (!loader->file_data) return FALSE; ASSERT_HEADER (loader->file_data_len >= h->header_size + h->color_map_entries * sizeof (XwdColor) + h->pixmap_height * (gsize) h->bytes_per_line); loader->image_data = (const guint8 *) loader->file_data + h->header_size + h->color_map_entries * sizeof (XwdColor); return TRUE; }
{'added': [(168, '#define UNPACK_FIELD_U32(dest, src, field) ((dest)->field = GUINT32_FROM_BE ((src)->field))'), (169, '#define UNPACK_FIELD_S32(dest, src, field) ((dest)->field = GINT32_FROM_BE ((src)->field))'), (172, 'load_header (XwdLoader *loader)'), (176, ' const XwdHeader *inp;'), (181, ' inp = &in;'), (182, ''), (183, ' UNPACK_FIELD_U32 (h, inp, header_size);'), (184, ' UNPACK_FIELD_U32 (h, inp, file_version);'), (185, ' UNPACK_FIELD_U32 (h, inp, pixmap_format);'), (186, ' UNPACK_FIELD_U32 (h, inp, pixmap_depth);'), (187, ' UNPACK_FIELD_U32 (h, inp, pixmap_width);'), (188, ' UNPACK_FIELD_U32 (h, inp, pixmap_height);'), (189, ' UNPACK_FIELD_U32 (h, inp, x_offset);'), (190, ' UNPACK_FIELD_U32 (h, inp, byte_order);'), (191, ' UNPACK_FIELD_U32 (h, inp, bitmap_unit);'), (192, ' UNPACK_FIELD_U32 (h, inp, bitmap_bit_order);'), (193, ' UNPACK_FIELD_U32 (h, inp, bitmap_pad);'), (194, ' UNPACK_FIELD_U32 (h, inp, bits_per_pixel);'), (195, ' UNPACK_FIELD_U32 (h, inp, bytes_per_line);'), (196, ' UNPACK_FIELD_U32 (h, inp, visual_class);'), (197, ' UNPACK_FIELD_U32 (h, inp, red_mask);'), (198, ' UNPACK_FIELD_U32 (h, inp, green_mask);'), (199, ' UNPACK_FIELD_U32 (h, inp, blue_mask);'), (200, ' UNPACK_FIELD_U32 (h, inp, bits_per_rgb);'), (201, ' UNPACK_FIELD_U32 (h, inp, color_map_entries);'), (202, ' UNPACK_FIELD_U32 (h, inp, n_colors);'), (203, ' UNPACK_FIELD_U32 (h, inp, window_width);'), (204, ' UNPACK_FIELD_U32 (h, inp, window_height);'), (205, ' UNPACK_FIELD_S32 (h, inp, window_x);'), (206, ' UNPACK_FIELD_S32 (h, inp, window_y);'), (207, ' UNPACK_FIELD_U32 (h, inp, window_border_width);'), (210, ' * namely, that corresponding to screen dumps from modern X.Org servers.'), (211, ' * We could check visual_class == 5 too, but the other fields convey all'), (212, ' * the info we need. */'), (215, ' ASSERT_HEADER (h->header_size <= 65535);'), (219, ' /* Should be zero for truecolor/directcolor. Cap it to prevent overflows. */'), (220, ' ASSERT_HEADER (h->color_map_entries <= 256);'), (221, ''), (226, ' /* These are the pixel formats we allow. */'), (227, ' ASSERT_HEADER (h->bits_per_pixel == 24 || h->bits_per_pixel == 32);'), (228, ''), (229, ' /* Enforce sane dimensions. */'), (230, ' ASSERT_HEADER (h->pixmap_width >= 1 && h->pixmap_width <= 65535);'), (231, ' ASSERT_HEADER (h->pixmap_height >= 1 && h->pixmap_height <= 65535);'), (232, ''), (233, " /* Make sure rowstride can actually hold a row's worth of data but is not padded to"), (234, ' * something ridiculous. */'), (236, ' ASSERT_HEADER (h->bytes_per_line <= h->pixmap_width * (h->bits_per_pixel / 8) + 1024);'), (237, ''), (238, ' /* Make sure the total allocation/map is not too big. */'), (239, ' ASSERT_HEADER (h->bytes_per_line * h->pixmap_height < (1UL << 31) - 65536 - 256 * 32);'), (240, ''), (248, ' + h->color_map_entries * sizeof (XwdColor)'), (249, ' + h->pixmap_height * (gsize) h->bytes_per_line);'), (252, ' + h->header_size + h->color_map_entries * sizeof (XwdColor);')], 'deleted': [(170, 'load_header (XwdLoader *loader) // gconstpointer in, gsize in_max_len, XwdHeader *header_out)'), (174, ' const guint32 *p = (const guint32 *) &in;'), (179, ' h->header_size = g_ntohl (*(p++));'), (180, ' h->file_version = g_ntohl (*(p++));'), (181, ' h->pixmap_format = g_ntohl (*(p++));'), (182, ' h->pixmap_depth = g_ntohl (*(p++));'), (183, ' h->pixmap_width = g_ntohl (*(p++));'), (184, ' h->pixmap_height = g_ntohl (*(p++));'), (185, ' h->x_offset = g_ntohl (*(p++));'), (186, ' h->byte_order = g_ntohl (*(p++));'), (187, ' h->bitmap_unit = g_ntohl (*(p++));'), (188, ' h->bitmap_bit_order = g_ntohl (*(p++));'), (189, ' h->bitmap_pad = g_ntohl (*(p++));'), (190, ' h->bits_per_pixel = g_ntohl (*(p++));'), (191, ' h->bytes_per_line = g_ntohl (*(p++));'), (192, ' h->visual_class = g_ntohl (*(p++));'), (193, ' h->red_mask = g_ntohl (*(p++));'), (194, ' h->green_mask = g_ntohl (*(p++));'), (195, ' h->blue_mask = g_ntohl (*(p++));'), (196, ' h->bits_per_rgb = g_ntohl (*(p++));'), (197, ' h->color_map_entries = g_ntohl (*(p++));'), (198, ' h->n_colors = g_ntohl (*(p++));'), (199, ' h->window_width = g_ntohl (*(p++));'), (200, ' h->window_height = g_ntohl (*(p++));'), (201, ' h->window_x = g_ntohl (*(p++));'), (202, ' h->window_y = g_ntohl (*(p++));'), (203, ' h->window_border_width = g_ntohl (*(p++));'), (206, ' * namely, that corresponding to screen dumps from modern X.Org servers. */'), (224, ' + h->n_colors * sizeof (XwdColor)'), (225, ' + h->pixmap_height * h->bytes_per_line);'), (228, ' + h->header_size + h->n_colors * sizeof (XwdColor);')]}
55
31
265
1,262
https://github.com/hpjansson/chafa
CVE-2022-2301
['CWE-125']
print-rpki-rtr.c
rpki_rtr_pdu_print
/* * Copyright (c) 1998-2011 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource Public Key Infrastructure (RPKI) to Router Protocol printer */ /* specification: RFC 6810 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" static const char tstr[] = "[|RPKI-RTR]"; /* * RPKI/Router PDU header * * Here's what the PDU header looks like. * The length does include the version and length fields. */ typedef struct rpki_rtr_pdu_ { u_char version; /* Version number */ u_char pdu_type; /* PDU type */ union { u_char session_id[2]; /* Session id */ u_char error_code[2]; /* Error code */ } u; u_char length[4]; } rpki_rtr_pdu; #define RPKI_RTR_PDU_OVERHEAD (offsetof(rpki_rtr_pdu, rpki_rtr_pdu_msg)) /* * IPv4 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv4_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[4]; u_char as[4]; } rpki_rtr_pdu_ipv4_prefix; /* * IPv6 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv6_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[16]; u_char as[4]; } rpki_rtr_pdu_ipv6_prefix; /* * Error report PDU. */ typedef struct rpki_rtr_pdu_error_report_ { rpki_rtr_pdu pdu_header; u_char encapsulated_pdu_length[4]; /* Encapsulated PDU length */ } rpki_rtr_pdu_error_report; /* * PDU type codes */ #define RPKI_RTR_SERIAL_NOTIFY_PDU 0 #define RPKI_RTR_SERIAL_QUERY_PDU 1 #define RPKI_RTR_RESET_QUERY_PDU 2 #define RPKI_RTR_CACHE_RESPONSE_PDU 3 #define RPKI_RTR_IPV4_PREFIX_PDU 4 #define RPKI_RTR_IPV6_PREFIX_PDU 6 #define RPKI_RTR_END_OF_DATA_PDU 7 #define RPKI_RTR_CACHE_RESET_PDU 8 #define RPKI_RTR_ERROR_REPORT_PDU 10 static const struct tok rpki_rtr_pdu_values[] = { { RPKI_RTR_SERIAL_NOTIFY_PDU, "Serial Notify" }, { RPKI_RTR_SERIAL_QUERY_PDU, "Serial Query" }, { RPKI_RTR_RESET_QUERY_PDU, "Reset Query" }, { RPKI_RTR_CACHE_RESPONSE_PDU, "Cache Response" }, { RPKI_RTR_IPV4_PREFIX_PDU, "IPV4 Prefix" }, { RPKI_RTR_IPV6_PREFIX_PDU, "IPV6 Prefix" }, { RPKI_RTR_END_OF_DATA_PDU, "End of Data" }, { RPKI_RTR_CACHE_RESET_PDU, "Cache Reset" }, { RPKI_RTR_ERROR_REPORT_PDU, "Error Report" }, { 0, NULL} }; static const struct tok rpki_rtr_error_codes[] = { { 0, "Corrupt Data" }, { 1, "Internal Error" }, { 2, "No Data Available" }, { 3, "Invalid Request" }, { 4, "Unsupported Protocol Version" }, { 5, "Unsupported PDU Type" }, { 6, "Withdrawal of Unknown Record" }, { 7, "Duplicate Announcement Received" }, { 0, NULL} }; /* * Build a indentation string for a given indentation level. * XXX this should be really in util.c */ static char * indent_string (u_int indent) { static char buf[20]; u_int idx; idx = 0; buf[idx] = '\0'; /* * Does the static buffer fit ? */ if (sizeof(buf) < ((indent/8) + (indent %8) + 2)) { return buf; } /* * Heading newline. */ buf[idx] = '\n'; idx++; while (indent >= 8) { buf[idx] = '\t'; idx++; indent -= 8; } while (indent > 0) { buf[idx] = ' '; idx++; indent--; } /* * Trailing zero. */ buf[idx] = '\0'; return buf; } /* * Print a single PDU. */ static int rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); ND_TCHECK2(*tptr, encapsulated_pdu_length); tlen = pdu_len; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); tptr += sizeof(*pdu); tlen -= sizeof(*pdu); /* * Recurse if there is an encapsulated PDU. */ if (encapsulated_pdu_length && (encapsulated_pdu_length <= tlen)) { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); if (rpki_rtr_pdu_print(ndo, tptr, indent+2)) goto trunc; } tptr += encapsulated_pdu_length; tlen -= encapsulated_pdu_length; /* * Extract, trail-zero and print the Error message. */ text_length = 0; if (tlen > 4) { text_length = EXTRACT_32BITS(tptr); tptr += 4; tlen -= 4; } ND_TCHECK2(*tptr, text_length); if (text_length && (text_length <= tlen )) { ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return 0; trunc: return 1; } void rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
/* * Copyright (c) 1998-2011 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource Public Key Infrastructure (RPKI) to Router Protocol printer */ /* specification: RFC 6810 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" static const char tstr[] = "[|RPKI-RTR]"; /* * RPKI/Router PDU header * * Here's what the PDU header looks like. * The length does include the version and length fields. */ typedef struct rpki_rtr_pdu_ { u_char version; /* Version number */ u_char pdu_type; /* PDU type */ union { u_char session_id[2]; /* Session id */ u_char error_code[2]; /* Error code */ } u; u_char length[4]; } rpki_rtr_pdu; #define RPKI_RTR_PDU_OVERHEAD (offsetof(rpki_rtr_pdu, rpki_rtr_pdu_msg)) /* * IPv4 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv4_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[4]; u_char as[4]; } rpki_rtr_pdu_ipv4_prefix; /* * IPv6 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv6_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[16]; u_char as[4]; } rpki_rtr_pdu_ipv6_prefix; /* * Error report PDU. */ typedef struct rpki_rtr_pdu_error_report_ { rpki_rtr_pdu pdu_header; u_char encapsulated_pdu_length[4]; /* Encapsulated PDU length */ /* Copy of Erroneous PDU (variable, optional) */ /* Length of Error Text (4 octets in network byte order) */ /* Arbitrary Text of Error Diagnostic Message (variable, optional) */ } rpki_rtr_pdu_error_report; /* * PDU type codes */ #define RPKI_RTR_SERIAL_NOTIFY_PDU 0 #define RPKI_RTR_SERIAL_QUERY_PDU 1 #define RPKI_RTR_RESET_QUERY_PDU 2 #define RPKI_RTR_CACHE_RESPONSE_PDU 3 #define RPKI_RTR_IPV4_PREFIX_PDU 4 #define RPKI_RTR_IPV6_PREFIX_PDU 6 #define RPKI_RTR_END_OF_DATA_PDU 7 #define RPKI_RTR_CACHE_RESET_PDU 8 #define RPKI_RTR_ERROR_REPORT_PDU 10 static const struct tok rpki_rtr_pdu_values[] = { { RPKI_RTR_SERIAL_NOTIFY_PDU, "Serial Notify" }, { RPKI_RTR_SERIAL_QUERY_PDU, "Serial Query" }, { RPKI_RTR_RESET_QUERY_PDU, "Reset Query" }, { RPKI_RTR_CACHE_RESPONSE_PDU, "Cache Response" }, { RPKI_RTR_IPV4_PREFIX_PDU, "IPV4 Prefix" }, { RPKI_RTR_IPV6_PREFIX_PDU, "IPV6 Prefix" }, { RPKI_RTR_END_OF_DATA_PDU, "End of Data" }, { RPKI_RTR_CACHE_RESET_PDU, "Cache Reset" }, { RPKI_RTR_ERROR_REPORT_PDU, "Error Report" }, { 0, NULL} }; static const struct tok rpki_rtr_error_codes[] = { { 0, "Corrupt Data" }, { 1, "Internal Error" }, { 2, "No Data Available" }, { 3, "Invalid Request" }, { 4, "Unsupported Protocol Version" }, { 5, "Unsupported PDU Type" }, { 6, "Withdrawal of Unknown Record" }, { 7, "Duplicate Announcement Received" }, { 0, NULL} }; /* * Build a indentation string for a given indentation level. * XXX this should be really in util.c */ static char * indent_string (u_int indent) { static char buf[20]; u_int idx; idx = 0; buf[idx] = '\0'; /* * Does the static buffer fit ? */ if (sizeof(buf) < ((indent/8) + (indent %8) + 2)) { return buf; } /* * Heading newline. */ buf[idx] = '\n'; idx++; while (indent >= 8) { buf[idx] = '\t'; idx++; indent -= 8; } while (indent > 0) { buf[idx] = ' '; idx++; indent--; } /* * Trailing zero. */ buf[idx] = '\0'; return buf; } /* * Print a single PDU. */ static u_int rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, const u_int len, const u_char recurse, const u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; /* Protocol Version */ ND_TCHECK_8BITS(tptr); if (*tptr != 0) { /* Skip the rest of the input buffer because even if this is * a well-formed PDU of a future RPKI-Router protocol version * followed by a well-formed PDU of RPKI-Router protocol * version 0, there is no way to know exactly how to skip the * current PDU. */ ND_PRINT((ndo, "%sRPKI-RTRv%u (unknown)", indent_string(8), *tptr)); return len; } if (len < sizeof(rpki_rtr_pdu)) { ND_PRINT((ndo, "(%u bytes is too few to decode)", len)); goto invalid; } ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); /* Do not check bounds with pdu_len yet, do it in the case blocks * below to make it possible to decode at least the beginning of * a truncated Error Report PDU or a truncated encapsulated PDU. */ hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); if (pdu_len < sizeof(rpki_rtr_pdu) || pdu_len > len) goto invalid; switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: if (pdu_len != sizeof(rpki_rtr_pdu) + 4) goto invalid; ND_TCHECK2(*tptr, pdu_len); msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 12) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 24) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; tlen = sizeof(rpki_rtr_pdu); /* Do not test for the "Length of Error Text" data element yet. */ if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Encapsulated PDU" * data element, more data elements may be present. */ pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); tlen += 4; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); if (encapsulated_pdu_length) { /* Section 5.10 of RFC 6810 says: * "An Error Report PDU MUST NOT be sent for an Error Report PDU." * * However, as far as the protocol encoding goes Error Report PDUs can * happen to be nested in each other, however many times, in which case * the decoder should still print such semantically incorrect PDUs. * * That said, "the Erroneous PDU field MAY be truncated" (ibid), thus * to keep things simple this implementation decodes only the two * outermost layers of PDUs and makes bounds checks in the outer and * the inner PDU independently. */ if (pdu_len < tlen + encapsulated_pdu_length) goto invalid; if (! recurse) { ND_TCHECK2(*tptr, tlen + encapsulated_pdu_length); } else { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); rpki_rtr_pdu_print(ndo, tptr + tlen, encapsulated_pdu_length, 0, indent + 2); } tlen += encapsulated_pdu_length; } if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Error Text" data element, * one more data element may be present. */ /* * Extract, trail-zero and print the Error message. */ text_length = EXTRACT_32BITS(tptr + tlen); tlen += 4; if (text_length) { if (pdu_len < tlen + text_length) goto invalid; /* fn_printn() makes the bounds check */ ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr + tlen, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: ND_TCHECK2(*tptr, pdu_len); /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return pdu_len; invalid: ND_PRINT((ndo, "%s", istr)); ND_TCHECK2(*tptr, len); return len; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); return len; } void rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (len) { u_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8); len -= pdu_len; pptr += pdu_len; } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); ND_TCHECK2(*tptr, encapsulated_pdu_length); tlen = pdu_len; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); tptr += sizeof(*pdu); tlen -= sizeof(*pdu); /* * Recurse if there is an encapsulated PDU. */ if (encapsulated_pdu_length && (encapsulated_pdu_length <= tlen)) { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); if (rpki_rtr_pdu_print(ndo, tptr, indent+2)) goto trunc; } tptr += encapsulated_pdu_length; tlen -= encapsulated_pdu_length; /* * Extract, trail-zero and print the Error message. */ text_length = 0; if (tlen > 4) { text_length = EXTRACT_32BITS(tptr); tptr += 4; tlen -= 4; } ND_TCHECK2(*tptr, text_length); if (text_length && (text_length <= tlen )) { ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return 0; trunc: return 1; }
rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, const u_int len, const u_char recurse, const u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; /* Protocol Version */ ND_TCHECK_8BITS(tptr); if (*tptr != 0) { /* Skip the rest of the input buffer because even if this is * a well-formed PDU of a future RPKI-Router protocol version * followed by a well-formed PDU of RPKI-Router protocol * version 0, there is no way to know exactly how to skip the * current PDU. */ ND_PRINT((ndo, "%sRPKI-RTRv%u (unknown)", indent_string(8), *tptr)); return len; } if (len < sizeof(rpki_rtr_pdu)) { ND_PRINT((ndo, "(%u bytes is too few to decode)", len)); goto invalid; } ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); /* Do not check bounds with pdu_len yet, do it in the case blocks * below to make it possible to decode at least the beginning of * a truncated Error Report PDU or a truncated encapsulated PDU. */ hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); if (pdu_len < sizeof(rpki_rtr_pdu) || pdu_len > len) goto invalid; switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: if (pdu_len != sizeof(rpki_rtr_pdu) + 4) goto invalid; ND_TCHECK2(*tptr, pdu_len); msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 12) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 24) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; tlen = sizeof(rpki_rtr_pdu); /* Do not test for the "Length of Error Text" data element yet. */ if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Encapsulated PDU" * data element, more data elements may be present. */ pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); tlen += 4; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); if (encapsulated_pdu_length) { /* Section 5.10 of RFC 6810 says: * "An Error Report PDU MUST NOT be sent for an Error Report PDU." * * However, as far as the protocol encoding goes Error Report PDUs can * happen to be nested in each other, however many times, in which case * the decoder should still print such semantically incorrect PDUs. * * That said, "the Erroneous PDU field MAY be truncated" (ibid), thus * to keep things simple this implementation decodes only the two * outermost layers of PDUs and makes bounds checks in the outer and * the inner PDU independently. */ if (pdu_len < tlen + encapsulated_pdu_length) goto invalid; if (! recurse) { ND_TCHECK2(*tptr, tlen + encapsulated_pdu_length); } else { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); rpki_rtr_pdu_print(ndo, tptr + tlen, encapsulated_pdu_length, 0, indent + 2); } tlen += encapsulated_pdu_length; } if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Error Text" data element, * one more data element may be present. */ /* * Extract, trail-zero and print the Error message. */ text_length = EXTRACT_32BITS(tptr + tlen); tlen += 4; if (text_length) { if (pdu_len < tlen + text_length) goto invalid; /* fn_printn() makes the bounds check */ ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr + tlen, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: ND_TCHECK2(*tptr, pdu_len); /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return pdu_len; invalid: ND_PRINT((ndo, "%s", istr)); ND_TCHECK2(*tptr, len); return len; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); return len; }
{'added': [(85, ' /* Copy of Erroneous PDU (variable, optional) */'), (86, ' /* Length of Error Text (4 octets in network byte order) */'), (87, ' /* Arbitrary Text of Error Diagnostic Message (variable, optional) */'), (177, 'static u_int'), (178, 'rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, const u_int len,'), (179, '\tconst u_char recurse, const u_int indent)'), (185, ' /* Protocol Version */'), (186, ' ND_TCHECK_8BITS(tptr);'), (187, ' if (*tptr != 0) {'), (188, '\t/* Skip the rest of the input buffer because even if this is'), (189, '\t * a well-formed PDU of a future RPKI-Router protocol version'), (190, '\t * followed by a well-formed PDU of RPKI-Router protocol'), (191, '\t * version 0, there is no way to know exactly how to skip the'), (192, '\t * current PDU.'), (193, '\t */'), (194, '\tND_PRINT((ndo, "%sRPKI-RTRv%u (unknown)", indent_string(8), *tptr));'), (195, '\treturn len;'), (196, ' }'), (197, ' if (len < sizeof(rpki_rtr_pdu)) {'), (198, '\tND_PRINT((ndo, "(%u bytes is too few to decode)", len));'), (199, '\tgoto invalid;'), (200, ' }'), (201, ' ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));'), (205, ' /* Do not check bounds with pdu_len yet, do it in the case blocks'), (206, ' * below to make it possible to decode at least the beginning of'), (207, ' * a truncated Error Report PDU or a truncated encapsulated PDU.'), (208, ' */'), (216, ' if (pdu_len < sizeof(rpki_rtr_pdu) || pdu_len > len)'), (217, '\tgoto invalid;'), (227, '\tif (pdu_len != sizeof(rpki_rtr_pdu) + 4)'), (228, '\t goto invalid;'), (229, '\tND_TCHECK2(*tptr, pdu_len);'), (242, '\tif (pdu_len != sizeof(rpki_rtr_pdu))'), (243, '\t goto invalid;'), (244, '\t/* no additional boundary to check */'), (252, '\tif (pdu_len != sizeof(rpki_rtr_pdu))'), (253, '\t goto invalid;'), (254, '\t/* no additional boundary to check */'), (264, '\t if (pdu_len != sizeof(rpki_rtr_pdu) + 12)'), (265, '\t\tgoto invalid;'), (266, '\t ND_TCHECK2(*tptr, pdu_len);'), (280, '\t if (pdu_len != sizeof(rpki_rtr_pdu) + 24)'), (281, '\t\tgoto invalid;'), (282, '\t ND_TCHECK2(*tptr, pdu_len);'), (297, '\t tlen = sizeof(rpki_rtr_pdu);'), (298, '\t /* Do not test for the "Length of Error Text" data element yet. */'), (299, '\t if (pdu_len < tlen + 4)'), (300, '\t\tgoto invalid;'), (301, '\t ND_TCHECK2(*tptr, tlen + 4);'), (302, '\t /* Safe up to and including the "Length of Encapsulated PDU"'), (303, '\t * data element, more data elements may be present.'), (304, '\t */'), (307, '\t tlen += 4;'), (315, '\t if (encapsulated_pdu_length) {'), (316, '\t\t/* Section 5.10 of RFC 6810 says:'), (317, '\t\t * "An Error Report PDU MUST NOT be sent for an Error Report PDU."'), (318, '\t\t *'), (319, '\t\t * However, as far as the protocol encoding goes Error Report PDUs can'), (320, '\t\t * happen to be nested in each other, however many times, in which case'), (321, '\t\t * the decoder should still print such semantically incorrect PDUs.'), (322, '\t\t *'), (323, '\t\t * That said, "the Erroneous PDU field MAY be truncated" (ibid), thus'), (324, '\t\t * to keep things simple this implementation decodes only the two'), (325, '\t\t * outermost layers of PDUs and makes bounds checks in the outer and'), (326, '\t\t * the inner PDU independently.'), (327, '\t\t */'), (328, '\t\tif (pdu_len < tlen + encapsulated_pdu_length)'), (329, '\t\t goto invalid;'), (330, '\t\tif (! recurse) {'), (331, '\t\t ND_TCHECK2(*tptr, tlen + encapsulated_pdu_length);'), (332, '\t\t}'), (333, '\t\telse {'), (334, '\t\t ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4)));'), (335, '\t\t rpki_rtr_pdu_print(ndo, tptr + tlen,'), (336, '\t\t\tencapsulated_pdu_length, 0, indent + 2);'), (337, '\t\t}'), (338, '\t\ttlen += encapsulated_pdu_length;'), (341, '\t if (pdu_len < tlen + 4)'), (342, '\t\tgoto invalid;'), (343, '\t ND_TCHECK2(*tptr, tlen + 4);'), (344, '\t /* Safe up to and including the "Length of Error Text" data element,'), (345, '\t * one more data element may be present.'), (346, '\t */'), (351, '\t text_length = EXTRACT_32BITS(tptr + tlen);'), (352, '\t tlen += 4;'), (353, ''), (354, '\t if (text_length) {'), (355, '\t\tif (pdu_len < tlen + text_length)'), (356, '\t\t goto invalid;'), (357, '\t\t/* fn_printn() makes the bounds check */'), (359, '\t\tif (fn_printn(ndo, tptr + tlen, text_length, ndo->ndo_snapend))'), (366, '\tND_TCHECK2(*tptr, pdu_len);'), (378, ' return pdu_len;'), (380, 'invalid:'), (381, ' ND_PRINT((ndo, "%s", istr));'), (382, ' ND_TCHECK2(*tptr, len);'), (383, ' return len;'), (385, ' ND_PRINT((ndo, "\\n\\t%s", tstr));'), (386, ' return len;'), (396, ' while (len) {'), (397, '\tu_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8);'), (398, '\tlen -= pdu_len;'), (399, '\tpptr += pdu_len;')], 'deleted': [(174, 'static int'), (175, 'rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent)'), (184, ' ND_TCHECK2(*tptr, pdu_len);'), (258, '\t ND_TCHECK2(*tptr, encapsulated_pdu_length);'), (259, '\t tlen = pdu_len;'), (267, '\t tptr += sizeof(*pdu);'), (268, '\t tlen -= sizeof(*pdu);'), (269, ''), (270, '\t /*'), (271, '\t * Recurse if there is an encapsulated PDU.'), (272, '\t */'), (273, '\t if (encapsulated_pdu_length &&'), (274, '\t\t(encapsulated_pdu_length <= tlen)) {'), (275, '\t\tND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4)));'), (276, '\t\tif (rpki_rtr_pdu_print(ndo, tptr, indent+2))'), (277, '\t\t\tgoto trunc;'), (280, '\t tptr += encapsulated_pdu_length;'), (281, '\t tlen -= encapsulated_pdu_length;'), (286, '\t text_length = 0;'), (287, '\t if (tlen > 4) {'), (288, '\t\ttext_length = EXTRACT_32BITS(tptr);'), (289, '\t\ttptr += 4;'), (290, '\t\ttlen -= 4;'), (291, '\t }'), (292, '\t ND_TCHECK2(*tptr, text_length);'), (293, '\t if (text_length && (text_length <= tlen )) {'), (295, '\t\tif (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend))'), (313, ' return 0;'), (316, ' return 1;'), (322, ' u_int tlen, pdu_type, pdu_len;'), (323, ' const u_char *tptr;'), (324, ' const rpki_rtr_pdu *pdu_header;'), (325, ''), (326, ' tptr = pptr;'), (327, ' tlen = len;'), (328, ''), (333, ''), (334, ' while (tlen >= sizeof(rpki_rtr_pdu)) {'), (335, ''), (336, ' ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));'), (337, ''), (338, '\tpdu_header = (const rpki_rtr_pdu *)tptr;'), (339, ' pdu_type = pdu_header->pdu_type;'), (340, ' pdu_len = EXTRACT_32BITS(pdu_header->length);'), (341, ' ND_TCHECK2(*tptr, pdu_len);'), (342, ''), (343, ' /* infinite loop check */'), (344, ' if (!pdu_type || !pdu_len) {'), (345, ' break;'), (346, ' }'), (347, ''), (348, ' if (tlen < pdu_len) {'), (349, ' goto trunc;'), (350, ' }'), (351, ''), (352, '\t/*'), (353, '\t * Print the PDU.'), (354, '\t */'), (355, '\tif (rpki_rtr_pdu_print(ndo, tptr, 8))'), (356, '\t\tgoto trunc;'), (357, ''), (358, ' tlen -= pdu_len;'), (359, ' tptr += pdu_len;'), (361, ' return;'), (362, 'trunc:'), (363, ' ND_PRINT((ndo, "\\n\\t%s", tstr));')]}
103
66
239
1,333
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13050
['CWE-125']
print-rpki-rtr.c
rpki_rtr_print
/* * Copyright (c) 1998-2011 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource Public Key Infrastructure (RPKI) to Router Protocol printer */ /* specification: RFC 6810 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" static const char tstr[] = "[|RPKI-RTR]"; /* * RPKI/Router PDU header * * Here's what the PDU header looks like. * The length does include the version and length fields. */ typedef struct rpki_rtr_pdu_ { u_char version; /* Version number */ u_char pdu_type; /* PDU type */ union { u_char session_id[2]; /* Session id */ u_char error_code[2]; /* Error code */ } u; u_char length[4]; } rpki_rtr_pdu; #define RPKI_RTR_PDU_OVERHEAD (offsetof(rpki_rtr_pdu, rpki_rtr_pdu_msg)) /* * IPv4 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv4_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[4]; u_char as[4]; } rpki_rtr_pdu_ipv4_prefix; /* * IPv6 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv6_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[16]; u_char as[4]; } rpki_rtr_pdu_ipv6_prefix; /* * Error report PDU. */ typedef struct rpki_rtr_pdu_error_report_ { rpki_rtr_pdu pdu_header; u_char encapsulated_pdu_length[4]; /* Encapsulated PDU length */ } rpki_rtr_pdu_error_report; /* * PDU type codes */ #define RPKI_RTR_SERIAL_NOTIFY_PDU 0 #define RPKI_RTR_SERIAL_QUERY_PDU 1 #define RPKI_RTR_RESET_QUERY_PDU 2 #define RPKI_RTR_CACHE_RESPONSE_PDU 3 #define RPKI_RTR_IPV4_PREFIX_PDU 4 #define RPKI_RTR_IPV6_PREFIX_PDU 6 #define RPKI_RTR_END_OF_DATA_PDU 7 #define RPKI_RTR_CACHE_RESET_PDU 8 #define RPKI_RTR_ERROR_REPORT_PDU 10 static const struct tok rpki_rtr_pdu_values[] = { { RPKI_RTR_SERIAL_NOTIFY_PDU, "Serial Notify" }, { RPKI_RTR_SERIAL_QUERY_PDU, "Serial Query" }, { RPKI_RTR_RESET_QUERY_PDU, "Reset Query" }, { RPKI_RTR_CACHE_RESPONSE_PDU, "Cache Response" }, { RPKI_RTR_IPV4_PREFIX_PDU, "IPV4 Prefix" }, { RPKI_RTR_IPV6_PREFIX_PDU, "IPV6 Prefix" }, { RPKI_RTR_END_OF_DATA_PDU, "End of Data" }, { RPKI_RTR_CACHE_RESET_PDU, "Cache Reset" }, { RPKI_RTR_ERROR_REPORT_PDU, "Error Report" }, { 0, NULL} }; static const struct tok rpki_rtr_error_codes[] = { { 0, "Corrupt Data" }, { 1, "Internal Error" }, { 2, "No Data Available" }, { 3, "Invalid Request" }, { 4, "Unsupported Protocol Version" }, { 5, "Unsupported PDU Type" }, { 6, "Withdrawal of Unknown Record" }, { 7, "Duplicate Announcement Received" }, { 0, NULL} }; /* * Build a indentation string for a given indentation level. * XXX this should be really in util.c */ static char * indent_string (u_int indent) { static char buf[20]; u_int idx; idx = 0; buf[idx] = '\0'; /* * Does the static buffer fit ? */ if (sizeof(buf) < ((indent/8) + (indent %8) + 2)) { return buf; } /* * Heading newline. */ buf[idx] = '\n'; idx++; while (indent >= 8) { buf[idx] = '\t'; idx++; indent -= 8; } while (indent > 0) { buf[idx] = ' '; idx++; indent--; } /* * Trailing zero. */ buf[idx] = '\0'; return buf; } /* * Print a single PDU. */ static int rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); ND_TCHECK2(*tptr, encapsulated_pdu_length); tlen = pdu_len; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); tptr += sizeof(*pdu); tlen -= sizeof(*pdu); /* * Recurse if there is an encapsulated PDU. */ if (encapsulated_pdu_length && (encapsulated_pdu_length <= tlen)) { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); if (rpki_rtr_pdu_print(ndo, tptr, indent+2)) goto trunc; } tptr += encapsulated_pdu_length; tlen -= encapsulated_pdu_length; /* * Extract, trail-zero and print the Error message. */ text_length = 0; if (tlen > 4) { text_length = EXTRACT_32BITS(tptr); tptr += 4; tlen -= 4; } ND_TCHECK2(*tptr, text_length); if (text_length && (text_length <= tlen )) { ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return 0; trunc: return 1; } void rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
/* * Copyright (c) 1998-2011 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource Public Key Infrastructure (RPKI) to Router Protocol printer */ /* specification: RFC 6810 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" static const char tstr[] = "[|RPKI-RTR]"; /* * RPKI/Router PDU header * * Here's what the PDU header looks like. * The length does include the version and length fields. */ typedef struct rpki_rtr_pdu_ { u_char version; /* Version number */ u_char pdu_type; /* PDU type */ union { u_char session_id[2]; /* Session id */ u_char error_code[2]; /* Error code */ } u; u_char length[4]; } rpki_rtr_pdu; #define RPKI_RTR_PDU_OVERHEAD (offsetof(rpki_rtr_pdu, rpki_rtr_pdu_msg)) /* * IPv4 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv4_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[4]; u_char as[4]; } rpki_rtr_pdu_ipv4_prefix; /* * IPv6 Prefix PDU. */ typedef struct rpki_rtr_pdu_ipv6_prefix_ { rpki_rtr_pdu pdu_header; u_char flags; u_char prefix_length; u_char max_length; u_char zero; u_char prefix[16]; u_char as[4]; } rpki_rtr_pdu_ipv6_prefix; /* * Error report PDU. */ typedef struct rpki_rtr_pdu_error_report_ { rpki_rtr_pdu pdu_header; u_char encapsulated_pdu_length[4]; /* Encapsulated PDU length */ /* Copy of Erroneous PDU (variable, optional) */ /* Length of Error Text (4 octets in network byte order) */ /* Arbitrary Text of Error Diagnostic Message (variable, optional) */ } rpki_rtr_pdu_error_report; /* * PDU type codes */ #define RPKI_RTR_SERIAL_NOTIFY_PDU 0 #define RPKI_RTR_SERIAL_QUERY_PDU 1 #define RPKI_RTR_RESET_QUERY_PDU 2 #define RPKI_RTR_CACHE_RESPONSE_PDU 3 #define RPKI_RTR_IPV4_PREFIX_PDU 4 #define RPKI_RTR_IPV6_PREFIX_PDU 6 #define RPKI_RTR_END_OF_DATA_PDU 7 #define RPKI_RTR_CACHE_RESET_PDU 8 #define RPKI_RTR_ERROR_REPORT_PDU 10 static const struct tok rpki_rtr_pdu_values[] = { { RPKI_RTR_SERIAL_NOTIFY_PDU, "Serial Notify" }, { RPKI_RTR_SERIAL_QUERY_PDU, "Serial Query" }, { RPKI_RTR_RESET_QUERY_PDU, "Reset Query" }, { RPKI_RTR_CACHE_RESPONSE_PDU, "Cache Response" }, { RPKI_RTR_IPV4_PREFIX_PDU, "IPV4 Prefix" }, { RPKI_RTR_IPV6_PREFIX_PDU, "IPV6 Prefix" }, { RPKI_RTR_END_OF_DATA_PDU, "End of Data" }, { RPKI_RTR_CACHE_RESET_PDU, "Cache Reset" }, { RPKI_RTR_ERROR_REPORT_PDU, "Error Report" }, { 0, NULL} }; static const struct tok rpki_rtr_error_codes[] = { { 0, "Corrupt Data" }, { 1, "Internal Error" }, { 2, "No Data Available" }, { 3, "Invalid Request" }, { 4, "Unsupported Protocol Version" }, { 5, "Unsupported PDU Type" }, { 6, "Withdrawal of Unknown Record" }, { 7, "Duplicate Announcement Received" }, { 0, NULL} }; /* * Build a indentation string for a given indentation level. * XXX this should be really in util.c */ static char * indent_string (u_int indent) { static char buf[20]; u_int idx; idx = 0; buf[idx] = '\0'; /* * Does the static buffer fit ? */ if (sizeof(buf) < ((indent/8) + (indent %8) + 2)) { return buf; } /* * Heading newline. */ buf[idx] = '\n'; idx++; while (indent >= 8) { buf[idx] = '\t'; idx++; indent -= 8; } while (indent > 0) { buf[idx] = ' '; idx++; indent--; } /* * Trailing zero. */ buf[idx] = '\0'; return buf; } /* * Print a single PDU. */ static u_int rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, const u_int len, const u_char recurse, const u_int indent) { const rpki_rtr_pdu *pdu_header; u_int pdu_type, pdu_len, hexdump; const u_char *msg; /* Protocol Version */ ND_TCHECK_8BITS(tptr); if (*tptr != 0) { /* Skip the rest of the input buffer because even if this is * a well-formed PDU of a future RPKI-Router protocol version * followed by a well-formed PDU of RPKI-Router protocol * version 0, there is no way to know exactly how to skip the * current PDU. */ ND_PRINT((ndo, "%sRPKI-RTRv%u (unknown)", indent_string(8), *tptr)); return len; } if (len < sizeof(rpki_rtr_pdu)) { ND_PRINT((ndo, "(%u bytes is too few to decode)", len)); goto invalid; } ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); /* Do not check bounds with pdu_len yet, do it in the case blocks * below to make it possible to decode at least the beginning of * a truncated Error Report PDU or a truncated encapsulated PDU. */ hexdump = FALSE; ND_PRINT((ndo, "%sRPKI-RTRv%u, %s PDU (%u), length: %u", indent_string(8), pdu_header->version, tok2str(rpki_rtr_pdu_values, "Unknown", pdu_type), pdu_type, pdu_len)); if (pdu_len < sizeof(rpki_rtr_pdu) || pdu_len > len) goto invalid; switch (pdu_type) { /* * The following PDUs share the message format. */ case RPKI_RTR_SERIAL_NOTIFY_PDU: case RPKI_RTR_SERIAL_QUERY_PDU: case RPKI_RTR_END_OF_DATA_PDU: if (pdu_len != sizeof(rpki_rtr_pdu) + 4) goto invalid; ND_TCHECK2(*tptr, pdu_len); msg = (const u_char *)(pdu_header + 1); ND_PRINT((ndo, "%sSession ID: 0x%04x, Serial: %u", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id), EXTRACT_32BITS(msg))); break; /* * The following PDUs share the message format. */ case RPKI_RTR_RESET_QUERY_PDU: case RPKI_RTR_CACHE_RESET_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ /* * Zero payload PDUs. */ break; case RPKI_RTR_CACHE_RESPONSE_PDU: if (pdu_len != sizeof(rpki_rtr_pdu)) goto invalid; /* no additional boundary to check */ ND_PRINT((ndo, "%sSession ID: 0x%04x", indent_string(indent+2), EXTRACT_16BITS(pdu_header->u.session_id))); break; case RPKI_RTR_IPV4_PREFIX_PDU: { const rpki_rtr_pdu_ipv4_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 12) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv4_prefix *)tptr; ND_PRINT((ndo, "%sIPv4 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ipaddr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_IPV6_PREFIX_PDU: { const rpki_rtr_pdu_ipv6_prefix *pdu; if (pdu_len != sizeof(rpki_rtr_pdu) + 24) goto invalid; ND_TCHECK2(*tptr, pdu_len); pdu = (const rpki_rtr_pdu_ipv6_prefix *)tptr; ND_PRINT((ndo, "%sIPv6 Prefix %s/%u-%u, origin-as %u, flags 0x%02x", indent_string(indent+2), ip6addr_string(ndo, pdu->prefix), pdu->prefix_length, pdu->max_length, EXTRACT_32BITS(pdu->as), pdu->flags)); } break; case RPKI_RTR_ERROR_REPORT_PDU: { const rpki_rtr_pdu_error_report *pdu; u_int encapsulated_pdu_length, text_length, tlen, error_code; tlen = sizeof(rpki_rtr_pdu); /* Do not test for the "Length of Error Text" data element yet. */ if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Encapsulated PDU" * data element, more data elements may be present. */ pdu = (const rpki_rtr_pdu_error_report *)tptr; encapsulated_pdu_length = EXTRACT_32BITS(pdu->encapsulated_pdu_length); tlen += 4; error_code = EXTRACT_16BITS(pdu->pdu_header.u.error_code); ND_PRINT((ndo, "%sError code: %s (%u), Encapsulated PDU length: %u", indent_string(indent+2), tok2str(rpki_rtr_error_codes, "Unknown", error_code), error_code, encapsulated_pdu_length)); if (encapsulated_pdu_length) { /* Section 5.10 of RFC 6810 says: * "An Error Report PDU MUST NOT be sent for an Error Report PDU." * * However, as far as the protocol encoding goes Error Report PDUs can * happen to be nested in each other, however many times, in which case * the decoder should still print such semantically incorrect PDUs. * * That said, "the Erroneous PDU field MAY be truncated" (ibid), thus * to keep things simple this implementation decodes only the two * outermost layers of PDUs and makes bounds checks in the outer and * the inner PDU independently. */ if (pdu_len < tlen + encapsulated_pdu_length) goto invalid; if (! recurse) { ND_TCHECK2(*tptr, tlen + encapsulated_pdu_length); } else { ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4))); rpki_rtr_pdu_print(ndo, tptr + tlen, encapsulated_pdu_length, 0, indent + 2); } tlen += encapsulated_pdu_length; } if (pdu_len < tlen + 4) goto invalid; ND_TCHECK2(*tptr, tlen + 4); /* Safe up to and including the "Length of Error Text" data element, * one more data element may be present. */ /* * Extract, trail-zero and print the Error message. */ text_length = EXTRACT_32BITS(tptr + tlen); tlen += 4; if (text_length) { if (pdu_len < tlen + text_length) goto invalid; /* fn_printn() makes the bounds check */ ND_PRINT((ndo, "%sError text: ", indent_string(indent+2))); if (fn_printn(ndo, tptr + tlen, text_length, ndo->ndo_snapend)) goto trunc; } } break; default: ND_TCHECK2(*tptr, pdu_len); /* * Unknown data, please hexdump. */ hexdump = TRUE; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo,tptr,"\n\t ", pdu_len); } return pdu_len; invalid: ND_PRINT((ndo, "%s", istr)); ND_TCHECK2(*tptr, len); return len; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); return len; } void rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (len) { u_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8); len -= pdu_len; pptr += pdu_len; } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { u_int tlen, pdu_type, pdu_len; const u_char *tptr; const rpki_rtr_pdu *pdu_header; tptr = pptr; tlen = len; if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (tlen >= sizeof(rpki_rtr_pdu)) { ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu)); pdu_header = (const rpki_rtr_pdu *)tptr; pdu_type = pdu_header->pdu_type; pdu_len = EXTRACT_32BITS(pdu_header->length); ND_TCHECK2(*tptr, pdu_len); /* infinite loop check */ if (!pdu_type || !pdu_len) { break; } if (tlen < pdu_len) { goto trunc; } /* * Print the PDU. */ if (rpki_rtr_pdu_print(ndo, tptr, 8)) goto trunc; tlen -= pdu_len; tptr += pdu_len; } return; trunc: ND_PRINT((ndo, "\n\t%s", tstr)); }
rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", RPKI-RTR")); return; } while (len) { u_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8); len -= pdu_len; pptr += pdu_len; } }
{'added': [(85, ' /* Copy of Erroneous PDU (variable, optional) */'), (86, ' /* Length of Error Text (4 octets in network byte order) */'), (87, ' /* Arbitrary Text of Error Diagnostic Message (variable, optional) */'), (177, 'static u_int'), (178, 'rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, const u_int len,'), (179, '\tconst u_char recurse, const u_int indent)'), (185, ' /* Protocol Version */'), (186, ' ND_TCHECK_8BITS(tptr);'), (187, ' if (*tptr != 0) {'), (188, '\t/* Skip the rest of the input buffer because even if this is'), (189, '\t * a well-formed PDU of a future RPKI-Router protocol version'), (190, '\t * followed by a well-formed PDU of RPKI-Router protocol'), (191, '\t * version 0, there is no way to know exactly how to skip the'), (192, '\t * current PDU.'), (193, '\t */'), (194, '\tND_PRINT((ndo, "%sRPKI-RTRv%u (unknown)", indent_string(8), *tptr));'), (195, '\treturn len;'), (196, ' }'), (197, ' if (len < sizeof(rpki_rtr_pdu)) {'), (198, '\tND_PRINT((ndo, "(%u bytes is too few to decode)", len));'), (199, '\tgoto invalid;'), (200, ' }'), (201, ' ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));'), (205, ' /* Do not check bounds with pdu_len yet, do it in the case blocks'), (206, ' * below to make it possible to decode at least the beginning of'), (207, ' * a truncated Error Report PDU or a truncated encapsulated PDU.'), (208, ' */'), (216, ' if (pdu_len < sizeof(rpki_rtr_pdu) || pdu_len > len)'), (217, '\tgoto invalid;'), (227, '\tif (pdu_len != sizeof(rpki_rtr_pdu) + 4)'), (228, '\t goto invalid;'), (229, '\tND_TCHECK2(*tptr, pdu_len);'), (242, '\tif (pdu_len != sizeof(rpki_rtr_pdu))'), (243, '\t goto invalid;'), (244, '\t/* no additional boundary to check */'), (252, '\tif (pdu_len != sizeof(rpki_rtr_pdu))'), (253, '\t goto invalid;'), (254, '\t/* no additional boundary to check */'), (264, '\t if (pdu_len != sizeof(rpki_rtr_pdu) + 12)'), (265, '\t\tgoto invalid;'), (266, '\t ND_TCHECK2(*tptr, pdu_len);'), (280, '\t if (pdu_len != sizeof(rpki_rtr_pdu) + 24)'), (281, '\t\tgoto invalid;'), (282, '\t ND_TCHECK2(*tptr, pdu_len);'), (297, '\t tlen = sizeof(rpki_rtr_pdu);'), (298, '\t /* Do not test for the "Length of Error Text" data element yet. */'), (299, '\t if (pdu_len < tlen + 4)'), (300, '\t\tgoto invalid;'), (301, '\t ND_TCHECK2(*tptr, tlen + 4);'), (302, '\t /* Safe up to and including the "Length of Encapsulated PDU"'), (303, '\t * data element, more data elements may be present.'), (304, '\t */'), (307, '\t tlen += 4;'), (315, '\t if (encapsulated_pdu_length) {'), (316, '\t\t/* Section 5.10 of RFC 6810 says:'), (317, '\t\t * "An Error Report PDU MUST NOT be sent for an Error Report PDU."'), (318, '\t\t *'), (319, '\t\t * However, as far as the protocol encoding goes Error Report PDUs can'), (320, '\t\t * happen to be nested in each other, however many times, in which case'), (321, '\t\t * the decoder should still print such semantically incorrect PDUs.'), (322, '\t\t *'), (323, '\t\t * That said, "the Erroneous PDU field MAY be truncated" (ibid), thus'), (324, '\t\t * to keep things simple this implementation decodes only the two'), (325, '\t\t * outermost layers of PDUs and makes bounds checks in the outer and'), (326, '\t\t * the inner PDU independently.'), (327, '\t\t */'), (328, '\t\tif (pdu_len < tlen + encapsulated_pdu_length)'), (329, '\t\t goto invalid;'), (330, '\t\tif (! recurse) {'), (331, '\t\t ND_TCHECK2(*tptr, tlen + encapsulated_pdu_length);'), (332, '\t\t}'), (333, '\t\telse {'), (334, '\t\t ND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4)));'), (335, '\t\t rpki_rtr_pdu_print(ndo, tptr + tlen,'), (336, '\t\t\tencapsulated_pdu_length, 0, indent + 2);'), (337, '\t\t}'), (338, '\t\ttlen += encapsulated_pdu_length;'), (341, '\t if (pdu_len < tlen + 4)'), (342, '\t\tgoto invalid;'), (343, '\t ND_TCHECK2(*tptr, tlen + 4);'), (344, '\t /* Safe up to and including the "Length of Error Text" data element,'), (345, '\t * one more data element may be present.'), (346, '\t */'), (351, '\t text_length = EXTRACT_32BITS(tptr + tlen);'), (352, '\t tlen += 4;'), (353, ''), (354, '\t if (text_length) {'), (355, '\t\tif (pdu_len < tlen + text_length)'), (356, '\t\t goto invalid;'), (357, '\t\t/* fn_printn() makes the bounds check */'), (359, '\t\tif (fn_printn(ndo, tptr + tlen, text_length, ndo->ndo_snapend))'), (366, '\tND_TCHECK2(*tptr, pdu_len);'), (378, ' return pdu_len;'), (380, 'invalid:'), (381, ' ND_PRINT((ndo, "%s", istr));'), (382, ' ND_TCHECK2(*tptr, len);'), (383, ' return len;'), (385, ' ND_PRINT((ndo, "\\n\\t%s", tstr));'), (386, ' return len;'), (396, ' while (len) {'), (397, '\tu_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8);'), (398, '\tlen -= pdu_len;'), (399, '\tpptr += pdu_len;')], 'deleted': [(174, 'static int'), (175, 'rpki_rtr_pdu_print (netdissect_options *ndo, const u_char *tptr, u_int indent)'), (184, ' ND_TCHECK2(*tptr, pdu_len);'), (258, '\t ND_TCHECK2(*tptr, encapsulated_pdu_length);'), (259, '\t tlen = pdu_len;'), (267, '\t tptr += sizeof(*pdu);'), (268, '\t tlen -= sizeof(*pdu);'), (269, ''), (270, '\t /*'), (271, '\t * Recurse if there is an encapsulated PDU.'), (272, '\t */'), (273, '\t if (encapsulated_pdu_length &&'), (274, '\t\t(encapsulated_pdu_length <= tlen)) {'), (275, '\t\tND_PRINT((ndo, "%s-----encapsulated PDU-----", indent_string(indent+4)));'), (276, '\t\tif (rpki_rtr_pdu_print(ndo, tptr, indent+2))'), (277, '\t\t\tgoto trunc;'), (280, '\t tptr += encapsulated_pdu_length;'), (281, '\t tlen -= encapsulated_pdu_length;'), (286, '\t text_length = 0;'), (287, '\t if (tlen > 4) {'), (288, '\t\ttext_length = EXTRACT_32BITS(tptr);'), (289, '\t\ttptr += 4;'), (290, '\t\ttlen -= 4;'), (291, '\t }'), (292, '\t ND_TCHECK2(*tptr, text_length);'), (293, '\t if (text_length && (text_length <= tlen )) {'), (295, '\t\tif (fn_printn(ndo, tptr, text_length, ndo->ndo_snapend))'), (313, ' return 0;'), (316, ' return 1;'), (322, ' u_int tlen, pdu_type, pdu_len;'), (323, ' const u_char *tptr;'), (324, ' const rpki_rtr_pdu *pdu_header;'), (325, ''), (326, ' tptr = pptr;'), (327, ' tlen = len;'), (328, ''), (333, ''), (334, ' while (tlen >= sizeof(rpki_rtr_pdu)) {'), (335, ''), (336, ' ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));'), (337, ''), (338, '\tpdu_header = (const rpki_rtr_pdu *)tptr;'), (339, ' pdu_type = pdu_header->pdu_type;'), (340, ' pdu_len = EXTRACT_32BITS(pdu_header->length);'), (341, ' ND_TCHECK2(*tptr, pdu_len);'), (342, ''), (343, ' /* infinite loop check */'), (344, ' if (!pdu_type || !pdu_len) {'), (345, ' break;'), (346, ' }'), (347, ''), (348, ' if (tlen < pdu_len) {'), (349, ' goto trunc;'), (350, ' }'), (351, ''), (352, '\t/*'), (353, '\t * Print the PDU.'), (354, '\t */'), (355, '\tif (rpki_rtr_pdu_print(ndo, tptr, 8))'), (356, '\t\tgoto trunc;'), (357, ''), (358, ' tlen -= pdu_len;'), (359, ' tptr += pdu_len;'), (361, ' return;'), (362, 'trunc:'), (363, ' ND_PRINT((ndo, "\\n\\t%s", tstr));')]}
103
66
239
1,333
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13050
['CWE-125']
fromgif.c
gif_process_raster
/* * This file is derived from "stb_image.h" that is in public domain. * https://github.com/nothings/stb * * Hayaki Saito <saitoha@me.com> modified this and re-licensed * it under the MIT license. * * Copyright (c) 2014-2018 Hayaki Saito * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "frame.h" #include "fromgif.h" /* * gif_context_t struct and start_xxx functions * * gif_context_t structure is our basic context used by all images, so it * contains all the IO context, plus some basic image information */ typedef struct { unsigned int img_x, img_y; int img_n, img_out_n; int buflen; unsigned char buffer_start[128]; unsigned char *img_buffer, *img_buffer_end; unsigned char *img_buffer_original; } gif_context_t; typedef struct { signed short prefix; unsigned char first; unsigned char suffix; } gif_lzw; typedef struct { int w, h; unsigned char *out; /* output buffer (always 4 components) */ int flags, bgindex, ratio, transparent, eflags; unsigned char pal[256][3]; unsigned char lpal[256][3]; gif_lzw codes[4096]; unsigned char *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; int loop_count; int delay; int is_multiframe; int is_terminated; } gif_t; /* initialize a memory-decode context */ static unsigned char gif_get8(gif_context_t *s) { if (s->img_buffer < s->img_buffer_end) { return *s->img_buffer++; } return 0; } static int gif_get16le(gif_context_t *s) { int z = gif_get8(s); return z + (gif_get8(s) << 8); } static void gif_parse_colortable( gif_context_t /* in */ *s, unsigned char /* in */ pal[256][3], int /* in */ num_entries) { int i; for (i = 0; i < num_entries; ++i) { pal[i][2] = gif_get8(s); pal[i][1] = gif_get8(s); pal[i][0] = gif_get8(s); } } static SIXELSTATUS gif_load_header( gif_context_t /* in */ *s, gif_t /* in */ *g) { SIXELSTATUS status = SIXEL_FALSE; unsigned char version; if (gif_get8(s) != 'G') { goto end; } if (gif_get8(s) != 'I') { goto end; } if (gif_get8(s) != 'F') { goto end; } if (gif_get8(s) != '8') { goto end; } version = gif_get8(s); if (version != '7' && version != '9') { goto end; } if (gif_get8(s) != 'a') { goto end; } g->w = gif_get16le(s); g->h = gif_get16le(s); g->flags = gif_get8(s); g->bgindex = gif_get8(s); g->ratio = gif_get8(s); g->transparent = (-1); g->loop_count = (-1); if (g->flags & 0x80) { gif_parse_colortable(s, g->pal, 2 << (g->flags & 7)); } status = SIXEL_OK; end: return status; } static SIXELSTATUS gif_init_frame( sixel_frame_t /* in */ *frame, gif_t /* in */ *pg, unsigned char /* in */ *bgcolor, int /* in */ reqcolors, int /* in */ fuse_palette) { SIXELSTATUS status = SIXEL_OK; int i; int ncolors; frame->delay = pg->delay; ncolors = 2 << (pg->flags & 7); if (frame->palette == NULL) { frame->palette = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(ncolors * 3)); } else if (frame->ncolors < ncolors) { sixel_allocator_free(frame->allocator, frame->palette); frame->palette = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(ncolors * 3)); } if (frame->palette == NULL) { sixel_helper_set_additional_message( "gif_init_frame: sixel_allocator_malloc() failed."); status = SIXEL_BAD_ALLOCATION; goto end; } frame->ncolors = ncolors; if (frame->ncolors <= reqcolors && fuse_palette) { frame->pixelformat = SIXEL_PIXELFORMAT_PAL8; sixel_allocator_free(frame->allocator, frame->pixels); frame->pixels = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(frame->width * frame->height)); if (frame->pixels == NULL) { sixel_helper_set_additional_message( "sixel_allocator_malloc() failed in gif_init_frame()."); status = SIXEL_BAD_ALLOCATION; goto end; } memcpy(frame->pixels, pg->out, (size_t)(frame->width * frame->height)); for (i = 0; i < frame->ncolors; ++i) { frame->palette[i * 3 + 0] = pg->color_table[i * 3 + 2]; frame->palette[i * 3 + 1] = pg->color_table[i * 3 + 1]; frame->palette[i * 3 + 2] = pg->color_table[i * 3 + 0]; } if (pg->lflags & 0x80) { if (pg->eflags & 0x01) { if (bgcolor) { frame->palette[pg->transparent * 3 + 0] = bgcolor[0]; frame->palette[pg->transparent * 3 + 1] = bgcolor[1]; frame->palette[pg->transparent * 3 + 2] = bgcolor[2]; } else { frame->transparent = pg->transparent; } } } else if (pg->flags & 0x80) { if (pg->eflags & 0x01) { if (bgcolor) { frame->palette[pg->transparent * 3 + 0] = bgcolor[0]; frame->palette[pg->transparent * 3 + 1] = bgcolor[1]; frame->palette[pg->transparent * 3 + 2] = bgcolor[2]; } else { frame->transparent = pg->transparent; } } } } else { frame->pixelformat = SIXEL_PIXELFORMAT_RGB888; frame->pixels = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(pg->w * pg->h * 3)); if (frame->pixels == NULL) { sixel_helper_set_additional_message( "sixel_allocator_malloc() failed in gif_init_frame()."); status = SIXEL_BAD_ALLOCATION; goto end; } for (i = 0; i < pg->w * pg->h; ++i) { frame->pixels[i * 3 + 0] = pg->color_table[pg->out[i] * 3 + 2]; frame->pixels[i * 3 + 1] = pg->color_table[pg->out[i] * 3 + 1]; frame->pixels[i * 3 + 2] = pg->color_table[pg->out[i] * 3 + 0]; } } frame->multiframe = (pg->loop_count != (-1)); status = SIXEL_OK; end: return status; } static void gif_out_code( gif_t /* in */ *g, unsigned short /* in */ code ) { /* recurse to decode the prefixes, since the linked-list is backwards, and working backwards through an interleaved image would be nasty */ if (g->codes[code].prefix >= 0) { gif_out_code(g, (unsigned short)g->codes[code].prefix); } if (g->cur_y >= g->max_y) { return; } g->out[g->cur_x + g->cur_y] = g->codes[code].suffix; g->cur_x++; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static SIXELSTATUS gif_process_raster( gif_context_t /* in */ *s, gif_t /* in */ *g ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char lzw_cs; signed int len, code; unsigned int first; signed int codesize, codemask, avail, oldcode, bits, valid_bits, clear; gif_lzw *p; lzw_cs = gif_get8(s); clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (code = 0; code < clear; code++) { g->codes[code].prefix = -1; g->codes[code].first = (unsigned char) code; g->codes[code].suffix = (unsigned char) code; } /* support no starting clear code */ avail = clear + 2; oldcode = (-1); len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = gif_get8(s); /* start new block */ if (len == 0) { return SIXEL_OK; } } --len; bits |= (signed int) gif_get8(s) << valid_bits; valid_bits += 8; } else { code = bits & codemask; bits >>= codesize; valid_bits -= codesize; /* @OPTIMIZE: is there some way we can accelerate the non-clear path? */ if (code == clear) { /* clear code */ codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { /* end of stream code */ s->img_buffer += len; while ((len = gif_get8(s)) > 0) { s->img_buffer += len; } return SIXEL_OK; } else if (code <= avail) { if (first) { sixel_helper_set_additional_message( "corrupt GIF (reason: no clear code)."); status = SIXEL_RUNTIME_ERROR; goto end; } if (oldcode >= 0) { if (avail < 4096) { p = &g->codes[avail++]; p->prefix = (signed short) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } } else if (code == avail) { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } gif_out_code(g, (unsigned short) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } } } status = SIXEL_OK; end: return status; } /* this function is ported from stb_image.h */ static SIXELSTATUS gif_load_next( gif_context_t /* in */ *s, gif_t /* in */ *g, unsigned char /* in */ *bgcolor ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char buffer[256]; int x; int y; int w; int h; int len; for (;;) { switch (gif_get8(s)) { case 0x2C: /* Image Descriptor */ x = gif_get16le(s); y = gif_get16le(s); w = gif_get16le(s); h = gif_get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) { sixel_helper_set_additional_message( "corrupt GIF (reason: bad Image Descriptor)."); status = SIXEL_RUNTIME_ERROR; goto end; } g->line_size = g->w; g->start_x = x; g->start_y = y * g->line_size; g->max_x = g->start_x + w; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; g->lflags = gif_get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; /* first interlaced spacing */ g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7)); g->color_table = (unsigned char *) g->lpal; } else if (g->flags & 0x80) { if (g->transparent >= 0 && (g->eflags & 0x01)) { if (bgcolor) { g->pal[g->transparent][0] = bgcolor[2]; g->pal[g->transparent][1] = bgcolor[1]; g->pal[g->transparent][2] = bgcolor[0]; } } g->color_table = (unsigned char *)g->pal; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: missing color table)."); status = SIXEL_RUNTIME_ERROR; goto end; } status = gif_process_raster(s, g); if (SIXEL_FAILED(status)) { goto end; } goto end; case 0x21: /* Comment Extension. */ switch (gif_get8(s)) { case 0x01: /* Plain Text Extension */ break; case 0x21: /* Comment Extension */ break; case 0xF9: /* Graphic Control Extension */ len = gif_get8(s); /* block size */ if (len == 4) { g->eflags = gif_get8(s); g->delay = gif_get16le(s); /* delay */ g->transparent = gif_get8(s); } else { s->img_buffer += len; break; } break; case 0xFF: /* Application Extension */ len = gif_get8(s); /* block size */ if (s->img_buffer + len > s->img_buffer_end) { status = SIXEL_RUNTIME_ERROR; goto end; } memcpy(buffer, s->img_buffer, (size_t)len); s->img_buffer += len; buffer[len] = 0; if (len == 11 && strcmp((char *)buffer, "NETSCAPE2.0") == 0) { if (gif_get8(s) == 0x03) { /* loop count */ switch (gif_get8(s)) { case 0x00: g->loop_count = 1; break; case 0x01: g->loop_count = gif_get16le(s); break; default: g->loop_count = 1; break; } } } break; default: break; } while ((len = gif_get8(s)) != 0) { s->img_buffer += len; } break; case 0x3B: /* gif stream termination code */ g->is_terminated = 1; status = SIXEL_OK; goto end; default: sixel_helper_set_additional_message( "corrupt GIF (reason: unknown code)."); status = SIXEL_RUNTIME_ERROR; goto end; } } status = SIXEL_OK; end: return status; } typedef union _fn_pointer { sixel_load_image_function fn; void * p; } fn_pointer; SIXELSTATUS load_gif( unsigned char /* in */ *buffer, int /* in */ size, unsigned char /* in */ *bgcolor, int /* in */ reqcolors, int /* in */ fuse_palette, int /* in */ fstatic, int /* in */ loop_control, void /* in */ *fn_load, /* callback */ void /* in */ *context, /* private data for callback */ sixel_allocator_t /* in */ *allocator) /* allocator object */ { gif_context_t s; gif_t g; SIXELSTATUS status = SIXEL_FALSE; sixel_frame_t *frame; fn_pointer fnp; fnp.p = fn_load; g.out = NULL; status = sixel_frame_new(&frame, allocator); if (SIXEL_FAILED(status)) { goto end; } s.img_buffer = s.img_buffer_original = (unsigned char *)buffer; s.img_buffer_end = (unsigned char *)buffer + size; memset(&g, 0, sizeof(g)); status = gif_load_header(&s, &g); if (status != SIXEL_OK) { goto end; } g.out = (unsigned char *)sixel_allocator_malloc(allocator, (size_t)(g.w * g.h)); if (g.out == NULL) { sixel_helper_set_additional_message( "load_gif: sixel_allocator_malloc() failed."); status = SIXEL_BAD_ALLOCATION; goto end; } frame->loop_count = 0; for (;;) { /* per loop */ frame->frame_no = 0; s.img_buffer = s.img_buffer_original; status = gif_load_header(&s, &g); if (status != SIXEL_OK) { goto end; } g.is_terminated = 0; for (;;) { /* per frame */ status = gif_load_next(&s, &g, bgcolor); if (status != SIXEL_OK) { goto end; } if (g.is_terminated) { break; } frame->width = g.w; frame->height = g.h; status = gif_init_frame(frame, &g, bgcolor, reqcolors, fuse_palette); if (status != SIXEL_OK) { goto end; } status = fnp.fn(frame, context); if (status != SIXEL_OK) { goto end; } if (fstatic) { goto end; } ++frame->frame_no; } ++frame->loop_count; if (g.loop_count < 0) { break; } if (loop_control == SIXEL_LOOP_DISABLE || frame->frame_no == 1) { break; } if (loop_control == SIXEL_LOOP_AUTO) { if (frame->loop_count == g.loop_count) { break; } } } end: sixel_allocator_free(frame->allocator, g.out); sixel_frame_unref(frame); return status; } #if HAVE_TESTS static int test1(void) { int nret = EXIT_FAILURE; nret = EXIT_SUCCESS; return nret; } SIXELAPI int sixel_fromgif_tests_main(void) { int nret = EXIT_FAILURE; size_t i; typedef int (* testcase)(void); static testcase const testcases[] = { test1, }; for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) { nret = testcases[i](); if (nret != EXIT_SUCCESS) { goto error; } } nret = EXIT_SUCCESS; error: return nret; } #endif /* HAVE_TESTS */ /* emacs Local Variables: */ /* emacs mode: c */ /* emacs tab-width: 4 */ /* emacs indent-tabs-mode: nil */ /* emacs c-basic-offset: 4 */ /* emacs End: */ /* vim: set expandtab ts=4 sts=4 sw=4 : */ /* EOF */
/* * This file is derived from "stb_image.h" that is in public domain. * https://github.com/nothings/stb * * Hayaki Saito <saitoha@me.com> modified this and re-licensed * it under the MIT license. * * Copyright (c) 2014-2018 Hayaki Saito * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "frame.h" #include "fromgif.h" /* * gif_context_t struct and start_xxx functions * * gif_context_t structure is our basic context used by all images, so it * contains all the IO context, plus some basic image information */ typedef struct { unsigned int img_x, img_y; int img_n, img_out_n; int buflen; unsigned char buffer_start[128]; unsigned char *img_buffer, *img_buffer_end; unsigned char *img_buffer_original; } gif_context_t; typedef struct { signed short prefix; unsigned char first; unsigned char suffix; } gif_lzw; enum { gif_lzw_max_code_size = 12 }; typedef struct { int w, h; unsigned char *out; /* output buffer (always 4 components) */ int flags, bgindex, ratio, transparent, eflags; unsigned char pal[256][3]; unsigned char lpal[256][3]; gif_lzw codes[1 << gif_lzw_max_code_size]; unsigned char *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; int loop_count; int delay; int is_multiframe; int is_terminated; } gif_t; /* initialize a memory-decode context */ static unsigned char gif_get8(gif_context_t *s) { if (s->img_buffer < s->img_buffer_end) { return *s->img_buffer++; } return 0; } static int gif_get16le(gif_context_t *s) { int z = gif_get8(s); return z + (gif_get8(s) << 8); } static void gif_parse_colortable( gif_context_t /* in */ *s, unsigned char /* in */ pal[256][3], int /* in */ num_entries) { int i; for (i = 0; i < num_entries; ++i) { pal[i][2] = gif_get8(s); pal[i][1] = gif_get8(s); pal[i][0] = gif_get8(s); } } static SIXELSTATUS gif_load_header( gif_context_t /* in */ *s, gif_t /* in */ *g) { SIXELSTATUS status = SIXEL_FALSE; unsigned char version; if (gif_get8(s) != 'G') { goto end; } if (gif_get8(s) != 'I') { goto end; } if (gif_get8(s) != 'F') { goto end; } if (gif_get8(s) != '8') { goto end; } version = gif_get8(s); if (version != '7' && version != '9') { goto end; } if (gif_get8(s) != 'a') { goto end; } g->w = gif_get16le(s); g->h = gif_get16le(s); g->flags = gif_get8(s); g->bgindex = gif_get8(s); g->ratio = gif_get8(s); g->transparent = (-1); g->loop_count = (-1); if (g->flags & 0x80) { gif_parse_colortable(s, g->pal, 2 << (g->flags & 7)); } status = SIXEL_OK; end: return status; } static SIXELSTATUS gif_init_frame( sixel_frame_t /* in */ *frame, gif_t /* in */ *pg, unsigned char /* in */ *bgcolor, int /* in */ reqcolors, int /* in */ fuse_palette) { SIXELSTATUS status = SIXEL_OK; int i; int ncolors; frame->delay = pg->delay; ncolors = 2 << (pg->flags & 7); if (frame->palette == NULL) { frame->palette = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(ncolors * 3)); } else if (frame->ncolors < ncolors) { sixel_allocator_free(frame->allocator, frame->palette); frame->palette = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(ncolors * 3)); } if (frame->palette == NULL) { sixel_helper_set_additional_message( "gif_init_frame: sixel_allocator_malloc() failed."); status = SIXEL_BAD_ALLOCATION; goto end; } frame->ncolors = ncolors; if (frame->ncolors <= reqcolors && fuse_palette) { frame->pixelformat = SIXEL_PIXELFORMAT_PAL8; sixel_allocator_free(frame->allocator, frame->pixels); frame->pixels = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(frame->width * frame->height)); if (frame->pixels == NULL) { sixel_helper_set_additional_message( "sixel_allocator_malloc() failed in gif_init_frame()."); status = SIXEL_BAD_ALLOCATION; goto end; } memcpy(frame->pixels, pg->out, (size_t)(frame->width * frame->height)); for (i = 0; i < frame->ncolors; ++i) { frame->palette[i * 3 + 0] = pg->color_table[i * 3 + 2]; frame->palette[i * 3 + 1] = pg->color_table[i * 3 + 1]; frame->palette[i * 3 + 2] = pg->color_table[i * 3 + 0]; } if (pg->lflags & 0x80) { if (pg->eflags & 0x01) { if (bgcolor) { frame->palette[pg->transparent * 3 + 0] = bgcolor[0]; frame->palette[pg->transparent * 3 + 1] = bgcolor[1]; frame->palette[pg->transparent * 3 + 2] = bgcolor[2]; } else { frame->transparent = pg->transparent; } } } else if (pg->flags & 0x80) { if (pg->eflags & 0x01) { if (bgcolor) { frame->palette[pg->transparent * 3 + 0] = bgcolor[0]; frame->palette[pg->transparent * 3 + 1] = bgcolor[1]; frame->palette[pg->transparent * 3 + 2] = bgcolor[2]; } else { frame->transparent = pg->transparent; } } } } else { frame->pixelformat = SIXEL_PIXELFORMAT_RGB888; frame->pixels = (unsigned char *)sixel_allocator_malloc(frame->allocator, (size_t)(pg->w * pg->h * 3)); if (frame->pixels == NULL) { sixel_helper_set_additional_message( "sixel_allocator_malloc() failed in gif_init_frame()."); status = SIXEL_BAD_ALLOCATION; goto end; } for (i = 0; i < pg->w * pg->h; ++i) { frame->pixels[i * 3 + 0] = pg->color_table[pg->out[i] * 3 + 2]; frame->pixels[i * 3 + 1] = pg->color_table[pg->out[i] * 3 + 1]; frame->pixels[i * 3 + 2] = pg->color_table[pg->out[i] * 3 + 0]; } } frame->multiframe = (pg->loop_count != (-1)); status = SIXEL_OK; end: return status; } static void gif_out_code( gif_t /* in */ *g, unsigned short /* in */ code ) { /* recurse to decode the prefixes, since the linked-list is backwards, and working backwards through an interleaved image would be nasty */ if (g->codes[code].prefix >= 0) { gif_out_code(g, (unsigned short)g->codes[code].prefix); } if (g->cur_y >= g->max_y) { return; } g->out[g->cur_x + g->cur_y] = g->codes[code].suffix; g->cur_x++; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static SIXELSTATUS gif_process_raster( gif_context_t /* in */ *s, gif_t /* in */ *g ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char lzw_cs; signed int len, code; unsigned int first; signed int codesize, codemask, avail, oldcode, bits, valid_bits, clear; gif_lzw *p; /* LZW Minimum Code Size */ lzw_cs = gif_get8(s); if (lzw_cs > gif_lzw_max_code_size) { sixel_helper_set_additional_message( "Unsupported GIF (LZW code size)"); status = SIXEL_RUNTIME_ERROR; goto end; } clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (code = 0; code < clear; code++) { g->codes[code].prefix = -1; g->codes[code].first = (unsigned char) code; g->codes[code].suffix = (unsigned char) code; } /* support no starting clear code */ avail = clear + 2; oldcode = (-1); len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = gif_get8(s); /* start new block */ if (len == 0) { return SIXEL_OK; } } --len; bits |= (signed int) gif_get8(s) << valid_bits; valid_bits += 8; } else { code = bits & codemask; bits >>= codesize; valid_bits -= codesize; /* @OPTIMIZE: is there some way we can accelerate the non-clear path? */ if (code == clear) { /* clear code */ codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { /* end of stream code */ s->img_buffer += len; while ((len = gif_get8(s)) > 0) { s->img_buffer += len; } return SIXEL_OK; } else if (code <= avail) { if (first) { sixel_helper_set_additional_message( "corrupt GIF (reason: no clear code)."); status = SIXEL_RUNTIME_ERROR; goto end; } if (oldcode >= 0) { if (avail < (1 << gif_lzw_max_code_size)) { p = &g->codes[avail++]; p->prefix = (signed short) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } } else if (code == avail) { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } gif_out_code(g, (unsigned short) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } } } status = SIXEL_OK; end: return status; } /* this function is ported from stb_image.h */ static SIXELSTATUS gif_load_next( gif_context_t /* in */ *s, gif_t /* in */ *g, unsigned char /* in */ *bgcolor ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char buffer[256]; int x; int y; int w; int h; int len; for (;;) { switch (gif_get8(s)) { case 0x2C: /* Image Descriptor */ x = gif_get16le(s); y = gif_get16le(s); w = gif_get16le(s); h = gif_get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) { sixel_helper_set_additional_message( "corrupt GIF (reason: bad Image Descriptor)."); status = SIXEL_RUNTIME_ERROR; goto end; } g->line_size = g->w; g->start_x = x; g->start_y = y * g->line_size; g->max_x = g->start_x + w; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; g->lflags = gif_get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; /* first interlaced spacing */ g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7)); g->color_table = (unsigned char *) g->lpal; } else if (g->flags & 0x80) { if (g->transparent >= 0 && (g->eflags & 0x01)) { if (bgcolor) { g->pal[g->transparent][0] = bgcolor[2]; g->pal[g->transparent][1] = bgcolor[1]; g->pal[g->transparent][2] = bgcolor[0]; } } g->color_table = (unsigned char *)g->pal; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: missing color table)."); status = SIXEL_RUNTIME_ERROR; goto end; } status = gif_process_raster(s, g); if (SIXEL_FAILED(status)) { goto end; } goto end; case 0x21: /* Comment Extension. */ switch (gif_get8(s)) { case 0x01: /* Plain Text Extension */ break; case 0x21: /* Comment Extension */ break; case 0xF9: /* Graphic Control Extension */ len = gif_get8(s); /* block size */ if (len == 4) { g->eflags = gif_get8(s); g->delay = gif_get16le(s); /* delay */ g->transparent = gif_get8(s); } else { s->img_buffer += len; break; } break; case 0xFF: /* Application Extension */ len = gif_get8(s); /* block size */ if (s->img_buffer + len > s->img_buffer_end) { status = SIXEL_RUNTIME_ERROR; goto end; } memcpy(buffer, s->img_buffer, (size_t)len); s->img_buffer += len; buffer[len] = 0; if (len == 11 && strcmp((char *)buffer, "NETSCAPE2.0") == 0) { if (gif_get8(s) == 0x03) { /* loop count */ switch (gif_get8(s)) { case 0x00: g->loop_count = 1; break; case 0x01: g->loop_count = gif_get16le(s); break; default: g->loop_count = 1; break; } } } break; default: break; } while ((len = gif_get8(s)) != 0) { s->img_buffer += len; } break; case 0x3B: /* gif stream termination code */ g->is_terminated = 1; status = SIXEL_OK; goto end; default: sixel_helper_set_additional_message( "corrupt GIF (reason: unknown code)."); status = SIXEL_RUNTIME_ERROR; goto end; } } status = SIXEL_OK; end: return status; } typedef union _fn_pointer { sixel_load_image_function fn; void * p; } fn_pointer; SIXELSTATUS load_gif( unsigned char /* in */ *buffer, int /* in */ size, unsigned char /* in */ *bgcolor, int /* in */ reqcolors, int /* in */ fuse_palette, int /* in */ fstatic, int /* in */ loop_control, void /* in */ *fn_load, /* callback */ void /* in */ *context, /* private data for callback */ sixel_allocator_t /* in */ *allocator) /* allocator object */ { gif_context_t s; gif_t g; SIXELSTATUS status = SIXEL_FALSE; sixel_frame_t *frame; fn_pointer fnp; fnp.p = fn_load; g.out = NULL; status = sixel_frame_new(&frame, allocator); if (SIXEL_FAILED(status)) { goto end; } s.img_buffer = s.img_buffer_original = (unsigned char *)buffer; s.img_buffer_end = (unsigned char *)buffer + size; memset(&g, 0, sizeof(g)); status = gif_load_header(&s, &g); if (status != SIXEL_OK) { goto end; } g.out = (unsigned char *)sixel_allocator_malloc(allocator, (size_t)(g.w * g.h)); if (g.out == NULL) { sixel_helper_set_additional_message( "load_gif: sixel_allocator_malloc() failed."); status = SIXEL_BAD_ALLOCATION; goto end; } frame->loop_count = 0; for (;;) { /* per loop */ frame->frame_no = 0; s.img_buffer = s.img_buffer_original; status = gif_load_header(&s, &g); if (status != SIXEL_OK) { goto end; } g.is_terminated = 0; for (;;) { /* per frame */ status = gif_load_next(&s, &g, bgcolor); if (status != SIXEL_OK) { goto end; } if (g.is_terminated) { break; } frame->width = g.w; frame->height = g.h; status = gif_init_frame(frame, &g, bgcolor, reqcolors, fuse_palette); if (status != SIXEL_OK) { goto end; } status = fnp.fn(frame, context); if (status != SIXEL_OK) { goto end; } if (fstatic) { goto end; } ++frame->frame_no; } ++frame->loop_count; if (g.loop_count < 0) { break; } if (loop_control == SIXEL_LOOP_DISABLE || frame->frame_no == 1) { break; } if (loop_control == SIXEL_LOOP_AUTO) { if (frame->loop_count == g.loop_count) { break; } } } end: sixel_allocator_free(frame->allocator, g.out); sixel_frame_unref(frame); return status; } #if HAVE_TESTS static int test1(void) { int nret = EXIT_FAILURE; nret = EXIT_SUCCESS; return nret; } SIXELAPI int sixel_fromgif_tests_main(void) { int nret = EXIT_FAILURE; size_t i; typedef int (* testcase)(void); static testcase const testcases[] = { test1, }; for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) { nret = testcases[i](); if (nret != EXIT_SUCCESS) { goto error; } } nret = EXIT_SUCCESS; error: return nret; } #endif /* HAVE_TESTS */ /* emacs Local Variables: */ /* emacs mode: c */ /* emacs tab-width: 4 */ /* emacs indent-tabs-mode: nil */ /* emacs c-basic-offset: 4 */ /* emacs End: */ /* vim: set expandtab ts=4 sts=4 sw=4 : */ /* EOF */
gif_process_raster( gif_context_t /* in */ *s, gif_t /* in */ *g ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char lzw_cs; signed int len, code; unsigned int first; signed int codesize, codemask, avail, oldcode, bits, valid_bits, clear; gif_lzw *p; lzw_cs = gif_get8(s); clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (code = 0; code < clear; code++) { g->codes[code].prefix = -1; g->codes[code].first = (unsigned char) code; g->codes[code].suffix = (unsigned char) code; } /* support no starting clear code */ avail = clear + 2; oldcode = (-1); len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = gif_get8(s); /* start new block */ if (len == 0) { return SIXEL_OK; } } --len; bits |= (signed int) gif_get8(s) << valid_bits; valid_bits += 8; } else { code = bits & codemask; bits >>= codesize; valid_bits -= codesize; /* @OPTIMIZE: is there some way we can accelerate the non-clear path? */ if (code == clear) { /* clear code */ codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { /* end of stream code */ s->img_buffer += len; while ((len = gif_get8(s)) > 0) { s->img_buffer += len; } return SIXEL_OK; } else if (code <= avail) { if (first) { sixel_helper_set_additional_message( "corrupt GIF (reason: no clear code)."); status = SIXEL_RUNTIME_ERROR; goto end; } if (oldcode >= 0) { if (avail < 4096) { p = &g->codes[avail++]; p->prefix = (signed short) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } } else if (code == avail) { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } gif_out_code(g, (unsigned short) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } } } status = SIXEL_OK; end: return status; }
gif_process_raster( gif_context_t /* in */ *s, gif_t /* in */ *g ) { SIXELSTATUS status = SIXEL_FALSE; unsigned char lzw_cs; signed int len, code; unsigned int first; signed int codesize, codemask, avail, oldcode, bits, valid_bits, clear; gif_lzw *p; /* LZW Minimum Code Size */ lzw_cs = gif_get8(s); if (lzw_cs > gif_lzw_max_code_size) { sixel_helper_set_additional_message( "Unsupported GIF (LZW code size)"); status = SIXEL_RUNTIME_ERROR; goto end; } clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (code = 0; code < clear; code++) { g->codes[code].prefix = -1; g->codes[code].first = (unsigned char) code; g->codes[code].suffix = (unsigned char) code; } /* support no starting clear code */ avail = clear + 2; oldcode = (-1); len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = gif_get8(s); /* start new block */ if (len == 0) { return SIXEL_OK; } } --len; bits |= (signed int) gif_get8(s) << valid_bits; valid_bits += 8; } else { code = bits & codemask; bits >>= codesize; valid_bits -= codesize; /* @OPTIMIZE: is there some way we can accelerate the non-clear path? */ if (code == clear) { /* clear code */ codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { /* end of stream code */ s->img_buffer += len; while ((len = gif_get8(s)) > 0) { s->img_buffer += len; } return SIXEL_OK; } else if (code <= avail) { if (first) { sixel_helper_set_additional_message( "corrupt GIF (reason: no clear code)."); status = SIXEL_RUNTIME_ERROR; goto end; } if (oldcode >= 0) { if (avail < (1 << gif_lzw_max_code_size)) { p = &g->codes[avail++]; p->prefix = (signed short) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } } else if (code == avail) { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } gif_out_code(g, (unsigned short) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { sixel_helper_set_additional_message( "corrupt GIF (reason: illegal code in raster)."); status = SIXEL_RUNTIME_ERROR; goto end; } } } status = SIXEL_OK; end: return status; }
{'added': [(61, 'enum {'), (62, ' gif_lzw_max_code_size = 12'), (63, '};'), (64, ''), (72, ' gif_lzw codes[1 << gif_lzw_max_code_size];'), (306, ' /* LZW Minimum Code Size */'), (308, ' if (lzw_cs > gif_lzw_max_code_size) {'), (309, ' sixel_helper_set_additional_message('), (310, ' "Unsupported GIF (LZW code size)");'), (311, ' status = SIXEL_RUNTIME_ERROR;'), (312, ' goto end;'), (313, ' }'), (314, ''), (368, ' if (avail < (1 << gif_lzw_max_code_size)) {')], 'deleted': [(68, ' gif_lzw codes[4096];'), (356, ' if (avail < 4096) {')]}
14
2
568
3,279
https://github.com/saitoha/libsixel
CVE-2020-21050
['CWE-787']
mat.c
ReadMATImage
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/distort.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/resource_.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned long ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #ifdef __WIN32__ "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f + GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q)); if (f+GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelRed(image,0,q); SetPixelGreen(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q+=GetPixelChannels(image); } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f+GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q)); if (f + GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+ (int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelRed(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(const Image *image,Quantum *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q); SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q); SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *CacheBlock, *DecompressBlock; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *)); if(CacheBlock==NULL) return NULL; DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(DecompressBlock==NULL) { RelinquishMagickMemory(CacheBlock); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; inflateInit(&zip_info); /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock); zip_info.next_in = (Bytef *) CacheBlock; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) DecompressBlock; status = inflate(&zip_info,Z_NO_FLUSH); extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file); (void) extent; if(status == Z_STREAM_END) goto DblBreak; } Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: (void) remove_utf8(clone_info->filename); return NULL; } return image2; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->flags^=CoderBlobSupportFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % MagickBooleanType WriteMATImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { ssize_t y; unsigned z; register const Quantum *p; unsigned int status; int logging; size_t DataSize; char padding; char MATLAB_HDR[0x80]; time_t current_time; struct tm local_time; unsigned char *pixels; int is_gray; MagickOffsetType scene; QuantumInfo *quantum_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); (void) logging; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace,exception); is_gray = SetImageGray(image,exception); z = is_gray ? 0 : 3; /* Store MAT header. */ DataSize = image->rows /*Y*/ * image->columns /*X*/; if(!is_gray) DataSize *= 3 /*Z*/; padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image, miMATRIX); (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56)); (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */ (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */ (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */ (void) WriteBlobLSBLong(image, 0); (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */ (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */ if(!is_gray) { (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image, 0); } (void) WriteBlobLSBShort(image, 1); /* 0xB0 */ (void) WriteBlobLSBShort(image, 1); /* 0xB2 */ (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */ /* Store image data. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); do { for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } while(z-- >= 2); while(padding-->0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/distort.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/resource_.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned long ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #ifdef __WIN32__ "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f + GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelBlue(image,q)); if (f+GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelRed(image,0,q); SetPixelGreen(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q+=GetPixelChannels(image); } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal, double MaxVal,ExceptionInfo *exception) { double f; int x; register Quantum *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (Quantum *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange-GetPixelRed(image,q)); if (f+GetPixelRed(image,q) > QuantumRange) SetPixelRed(image,QuantumRange,q); else SetPixelRed(image,GetPixelRed(image,q)+(int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); } else { SetPixelBlue(image,GetPixelBlue(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelBlue(image,q),q); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(image,q)); if (f + GetPixelBlue(image,q) > QuantumRange) SetPixelBlue(image,QuantumRange,q); else SetPixelBlue(image,GetPixelBlue(image,q)+ (int) f,q); if ((int) f / 2.0 > GetPixelGreen(image,q)) { SetPixelGreen(image,0,q); SetPixelRed(image,0,q); } else { SetPixelRed(image,GetPixelRed(image,q)-(int) (f/2.0),q); SetPixelGreen(image,GetPixelRed(image,q),q); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(const Image *image,Quantum *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q); SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q); SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *CacheBlock, *DecompressBlock; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *)); if(CacheBlock==NULL) return NULL; DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(DecompressBlock==NULL) { RelinquishMagickMemory(CacheBlock); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; inflateInit(&zip_info); /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock); zip_info.next_in = (Bytef *) CacheBlock; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) DecompressBlock; status = inflate(&zip_info,Z_NO_FLUSH); extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file); (void) extent; if(status == Z_STREAM_END) goto DblBreak; } Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: (void) remove_utf8(clone_info->filename); return NULL; } return image2; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->flags^=CoderBlobSupportFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % MagickBooleanType WriteMATImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { ssize_t y; unsigned z; register const Quantum *p; unsigned int status; int logging; size_t DataSize; char padding; char MATLAB_HDR[0x80]; time_t current_time; struct tm local_time; unsigned char *pixels; int is_gray; MagickOffsetType scene; QuantumInfo *quantum_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); (void) logging; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace,exception); is_gray = SetImageGray(image,exception); z = is_gray ? 0 : 3; /* Store MAT header. */ DataSize = image->rows /*Y*/ * image->columns /*X*/; if(!is_gray) DataSize *= 3 /*Z*/; padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image, miMATRIX); (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56)); (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */ (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */ (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */ (void) WriteBlobLSBLong(image, 0); (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */ (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */ if(!is_gray) { (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image, 0); } (void) WriteBlobLSBShort(image, 1); /* 0xB0 */ (void) WriteBlobLSBShort(image, 1); /* 0xB2 */ (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */ /* Store image data. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetQuantumPixels(quantum_info); do { for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } while(z-- >= 2); while(padding-->0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); }
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); }
{'added': [(867, ' BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */')], 'deleted': [(867, ' BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char)); /* Ldblk was set in the check phase */')]}
1
1
958
6,186
https://github.com/ImageMagick/ImageMagick
CVE-2016-10071
['CWE-125']
re_lexer.c
input
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c;
#else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c;
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
re_yyensure_buffer_stack
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
*/ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; }
*/ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; }
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
re_yyget_column
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
*/ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn;
*/ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn;
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
re_yyget_lineno
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
*/ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno;
*/ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno;
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
re_yylex_init_extra
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals );
int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals );
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
read_escaped_char
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1;
int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1;
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
re_lexer.c
while
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (text[2] == EOF) return 0; text[3] = RE_YY_INPUT(yyscanner); if (text[3] == EOF) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
#line 2 "re_lexer.c" #line 4 "re_lexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 6 #define YY_FLEX_SUBMINOR_VERSION 0 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE re_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE re_yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) #define YY_LINENO_REWIND_TO(dst) \ do {\ const char *p;\ for ( p = yy_cp-1; p >= (dst); --p)\ if ( *p == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via re_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void re_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void re_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void re_yypop_buffer_state (yyscan_t yyscanner ); static void re_yyensure_buffer_stack (yyscan_t yyscanner ); static void re_yy_load_buffer_state (yyscan_t yyscanner ); static void re_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER re_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE re_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE re_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *re_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *re_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void re_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer re_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ re_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define re_yywrap(yyscanner) (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__noreturn__)) #endif static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 29 #define YY_END_OF_BUFFER 30 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[45] = { 0, 0, 0, 0, 0, 30, 7, 7, 28, 6, 17, 7, 27, 29, 26, 18, 5, 3, 16, 15, 13, 11, 9, 14, 12, 10, 8, 0, 0, 0, 0, 25, 23, 21, 24, 22, 20, 0, 4, 0, 1, 2, 19, 0, 0 } ; static yyconst YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 3, 3, 3, 3, 4, 5, 3, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 3, 1, 7, 8, 7, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 11, 1, 1, 1, 12, 13, 14, 15, 1, 1, 7, 16, 7, 17, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 19, 20, 1, 1, 21, 3, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst YY_CHAR yy_meta[23] = { 0, 1, 2, 1, 1, 3, 4, 4, 4, 4, 1, 1, 1, 1, 5, 1, 4, 4, 1, 1, 1, 1, 1 } ; static yyconst flex_uint16_t yy_base[51] = { 0, 0, 20, 3, 5, 50, 89, 89, 89, 10, 36, 0, 44, 43, 47, 38, 89, 26, 33, 89, 89, 89, 89, 89, 89, 89, 89, 4, 5, 0, 33, 32, 31, 29, 26, 24, 23, 15, 89, 8, 89, 89, 89, 0, 89, 67, 72, 77, 82, 84, 4 } ; static yyconst flex_int16_t yy_def[51] = { 0, 45, 45, 46, 46, 44, 44, 44, 44, 44, 44, 44, 44, 44, 47, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 48, 44, 44, 44, 44, 44, 44, 44, 49, 44, 44, 44, 44, 44, 50, 0, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_uint16_t yy_nxt[112] = { 0, 44, 7, 8, 27, 13, 28, 13, 30, 27, 39, 28, 9, 10, 39, 8, 14, 15, 14, 15, 29, 11, 7, 8, 16, 17, 40, 41, 29, 29, 40, 29, 9, 10, 29, 8, 29, 29, 29, 18, 38, 11, 18, 29, 19, 20, 21, 22, 29, 29, 44, 44, 23, 24, 25, 26, 31, 32, 33, 44, 44, 44, 44, 44, 34, 35, 36, 37, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 30, 44, 30, 30, 30, 42, 42, 42, 42, 43, 43, 5, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; static yyconst flex_int16_t yy_chk[112] = { 0, 0, 1, 1, 11, 3, 11, 4, 50, 28, 27, 28, 1, 1, 39, 1, 3, 3, 4, 4, 37, 1, 2, 2, 9, 9, 27, 28, 36, 35, 39, 34, 2, 2, 33, 2, 32, 31, 30, 18, 17, 2, 10, 15, 10, 10, 10, 10, 13, 12, 5, 0, 10, 10, 10, 10, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 45, 45, 45, 45, 45, 46, 46, 46, 46, 46, 47, 0, 47, 47, 47, 48, 48, 48, 48, 49, 49, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[30] = { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "re_lexer.l" /* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /* Lexical analyzer for regular expressions */ #line 33 "re_lexer.l" /* Disable warnings for unused functions in this file. As we redefine YY_FATAL_ERROR macro to use our own function re_yyfatal, the yy_fatal_error function generated by Flex is not actually used, causing a compiler warning. Flex doesn't offer any options to remove the yy_fatal_error function. When they include something like %option noyy_fatal_error as they do with noyywrap then we can remove this pragma. */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" #endif #include <assert.h> #include <setjmp.h> #include <yara/utils.h> #include <yara/error.h> #include <yara/limits.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/re_lexer.h> #include <yara/threading.h> #include <yara/strutils.h> #ifdef _WIN32 #define snprintf _snprintf #endif static uint8_t word_chars[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0xFE, 0xFF, 0xFF, 0x87, 0xFE, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t escaped_char_value( char* text); int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char); #define YY_NO_UNISTD_H 1 #line 586 "re_lexer.c" #define INITIAL 0 #define char_class 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int re_yylex_init (yyscan_t* scanner); int re_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int re_yylex_destroy (yyscan_t yyscanner ); int re_yyget_debug (yyscan_t yyscanner ); void re_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner ); void re_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *re_yyget_in (yyscan_t yyscanner ); void re_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); FILE *re_yyget_out (yyscan_t yyscanner ); void re_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); yy_size_t re_yyget_leng (yyscan_t yyscanner ); char *re_yyget_text (yyscan_t yyscanner ); int re_yyget_lineno (yyscan_t yyscanner ); void re_yyset_lineno (int _line_number ,yyscan_t yyscanner ); int re_yyget_column (yyscan_t yyscanner ); void re_yyset_column (int _column_no ,yyscan_t yyscanner ); YYSTYPE * re_yyget_lval (yyscan_t yyscanner ); void re_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int re_yywrap (yyscan_t yyscanner ); #else extern int re_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef YY_NO_UNPUT #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int re_yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int re_yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_load_buffer_state(yyscanner ); } { #line 99 "re_lexer.l" #line 863 "re_lexer.c" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of user's declarations */ } /* end of re_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = yyg->yytext_ptr; yy_size_t number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ re_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; re_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) re_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { yy_state_type yy_current_state; char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ char *yy_cp = yyg->yy_c_buf_p; YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 44); (void)yyg; return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_UNPUT #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void re_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ re_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = re_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } re_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); re_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void re_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * re_yypop_buffer_state(); * re_yypush_buffer_state(new_buffer); */ re_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; re_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (re_yywrap()) processing, but the only time this flag * is looked at is after re_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void re_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE re_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_buf_size = (yy_size_t)size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) re_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_create_buffer()" ); b->yy_is_our_buffer = 1; re_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with re_yy_create_buffer() * @param yyscanner The scanner object. */ void re_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) re_yyfree((void *) b->yy_ch_buf ,yyscanner ); re_yyfree((void *) b ,yyscanner ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a re_yyrestart() or at EOF. */ static void re_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; re_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then re_yy_init_buffer was _probably_ * called from re_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void re_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; re_yyensure_buffer_stack(yyscanner); /* This block is copied from re_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from re_yy_switch_to_buffer. */ re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void re_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { re_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void re_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; // After all that talk, this was set to 1 anyways... yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) re_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; re_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to re_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * re_yy_scan_bytes() instead. */ YY_BUFFER_STATE re_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return re_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to re_yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE re_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; yy_size_t i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) re_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in re_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = re_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in re_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int re_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *re_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *re_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t re_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *re_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void re_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param _line_number line number * @param yyscanner The scanner object. */ void re_yyset_lineno (int _line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_lineno called with no buffer" ); yylineno = _line_number; } /** Set the current column. * @param _column_no column number * @param yyscanner The scanner object. */ void re_yyset_column (int _column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) YY_FATAL_ERROR( "re_yyset_column called with no buffer" ); yycolumn = _column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param _in_str A readable stream. * @param yyscanner The scanner object. * @see re_yy_switch_to_buffer */ void re_yyset_in (FILE * _in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = _in_str ; } void re_yyset_out (FILE * _out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = _out_str ; } int re_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void re_yyset_debug (int _bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = _bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * re_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void re_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* User-visible API */ /* re_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int re_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* re_yylex_init_extra has the same functionality as re_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to re_yyalloc in * the yyextra field. */ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from re_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * re_yylex_init() */ return 0; } /* re_yylex_destroy is for both reentrant and non-reentrant scanners. */ int re_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ re_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; re_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ re_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ re_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * re_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ re_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *re_yyalloc (yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; return (void *) malloc( size ); } void *re_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void re_yyfree (void * ptr , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; (void)yyg; free( (char *) ptr ); /* see re_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 464 "re_lexer.l" uint8_t escaped_char_value( char* text) { char hex[3]; int result; assert(text[0] == '\\'); switch(text[1]) { case 'x': hex[0] = text[2]; hex[1] = text[3]; hex[2] = '\0'; sscanf(hex, "%x", &result); break; case 'n': result = '\n'; break; case 't': result = '\t'; break; case 'r': result = '\r'; break; case 'f': result = '\f'; break; case 'a': result = '\a'; break; default: result = text[1]; } return result; } #ifdef __cplusplus #define RE_YY_INPUT yyinput #else #define RE_YY_INPUT input #endif int read_escaped_char( yyscan_t yyscanner, uint8_t* escaped_char) { char text[4] = {0, 0, 0, 0}; text[0] = '\\'; text[1] = RE_YY_INPUT(yyscanner); if (text[1] == EOF || text[1] == 0) return 0; if (text[1] == 'x') { text[2] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[2])) return 0; text[3] = RE_YY_INPUT(yyscanner); if (!isxdigit(text[3])) return 0; } *escaped_char = escaped_char_value(text); return 1; } extern YR_THREAD_STORAGE_KEY recovery_state_key; void yyfatal( yyscan_t yyscanner, const char *error_message) { jmp_buf* recovery_state = (jmp_buf*) yr_thread_storage_get_value( &recovery_state_key); longjmp(*recovery_state, 1); } void yyerror( yyscan_t yyscanner, RE_LEX_ENVIRONMENT* lex_env, const char *error_message) { // if lex_env->last_error_code was set to some error code before // don't overwrite it, we are interested in the first error, not in // subsequent errors like "syntax error, unexpected $end" caused by // early parser termination. if (lex_env->last_error_code == ERROR_SUCCESS) { lex_env->last_error_code = ERROR_INVALID_REGULAR_EXPRESSION; strlcpy( lex_env->last_error_message, error_message, sizeof(lex_env->last_error_message)); } } int yr_parse_re_string( const char* re_string, int flags, RE** re, RE_ERROR* error) { yyscan_t yyscanner; jmp_buf recovery_state; RE_LEX_ENVIRONMENT lex_env; lex_env.last_error_code = ERROR_SUCCESS; yr_thread_storage_set_value(&recovery_state_key, &recovery_state); if (setjmp(recovery_state) != 0) return ERROR_INTERNAL_FATAL_ERROR; FAIL_ON_ERROR(yr_re_create(re)); (*re)->flags = flags; re_yylex_init(&yyscanner); re_yyset_extra(*re,yyscanner); re_yy_scan_string(re_string,yyscanner); yyparse(yyscanner, &lex_env); re_yylex_destroy(yyscanner); if (lex_env.last_error_code != ERROR_SUCCESS) { yr_re_destroy(*re); *re = NULL; strlcpy( error->message, lex_env.last_error_message, sizeof(error->message)); return lex_env.last_error_code; } return ERROR_SUCCESS; }
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "illegal escape sequence"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */
{'added': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1183, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1295, ' yyerror(yyscanner, lex_env, "illegal escape sequence");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF || text[1] == 0)'), (2578, ' if (!isxdigit(text[2]))'), (2583, ' if (!isxdigit(text[3]))')], 'deleted': [(193, ' * existing scanners that call yyless() from OUTSIDE re_yylex.'), (269, ''), (909, ''), (1128, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1183, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1295, ' yyerror(yyscanner, lex_env, "unexpected end of buffer");'), (1766, ''), (2021, ''), (2023, ''), (2052, ' * @return the newly allocated buffer state object.'), (2180, ''), (2193, ''), (2368, ''), (2370, ''), (2375, ''), (2379, ''), (2381, ''), (2571, ' if (text[1] == EOF)'), (2578, ' if (text[2] == EOF)'), (2583, ' if (text[3] == EOF)')]}
20
20
1,368
7,959
https://github.com/VirusTotal/yara
CVE-2016-10210
['CWE-476']
user_defined.c
user_describe
/* user_defined.c: user defined key type * * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/user-type.h> #include <linux/uaccess.h> #include "internal.h" static int logon_vet_description(const char *desc); /* * user defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_user = { .name = "user", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; EXPORT_SYMBOL_GPL(key_type_user); /* * This key type is essentially the same as key_type_user, but it does * not define a .read op. This is suitable for storing username and * password pairs in the keyring that you do not want to be readable * from userspace. */ struct key_type key_type_logon = { .name = "logon", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .vet_description = logon_vet_description, }; EXPORT_SYMBOL_GPL(key_type_logon); /* * Preparse a user defined key payload */ int user_preparse(struct key_preparsed_payload *prep) { struct user_key_payload *upayload; size_t datalen = prep->datalen; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) return -ENOMEM; /* attach the data */ prep->quotalen = datalen; prep->payload.data[0] = upayload; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); return 0; } EXPORT_SYMBOL_GPL(user_preparse); /* * Free a preparse of a user defined key payload */ void user_free_preparse(struct key_preparsed_payload *prep) { kzfree(prep->payload.data[0]); } EXPORT_SYMBOL_GPL(user_free_preparse); static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } /* * update a user defined key * - the key's semaphore is write-locked */ int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } EXPORT_SYMBOL_GPL(user_update); /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void user_revoke(struct key *key) { struct user_key_payload *upayload = user_key_payload_locked(key); /* clear the quota */ key_payload_reserve(key, 0); if (upayload) { rcu_assign_keypointer(key, NULL); call_rcu(&upayload->rcu, user_free_payload_rcu); } } EXPORT_SYMBOL(user_revoke); /* * dispose of the data dangling from the corpse of a user key */ void user_destroy(struct key *key) { struct user_key_payload *upayload = key->payload.data[0]; kzfree(upayload); } EXPORT_SYMBOL_GPL(user_destroy); /* * describe the user key */ void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); } EXPORT_SYMBOL_GPL(user_describe); /* * read the key data * - the key's semaphore is read-locked */ long user_read(const struct key *key, char __user *buffer, size_t buflen) { const struct user_key_payload *upayload; long ret; upayload = user_key_payload_locked(key); ret = upayload->datalen; /* we can return the data as is */ if (buffer && buflen > 0) { if (buflen > upayload->datalen) buflen = upayload->datalen; if (copy_to_user(buffer, upayload->data, buflen) != 0) ret = -EFAULT; } return ret; } EXPORT_SYMBOL_GPL(user_read); /* Vet the description for a "logon" key */ static int logon_vet_description(const char *desc) { char *p; /* require a "qualified" description string */ p = strchr(desc, ':'); if (!p) return -EINVAL; /* also reject description with ':' as first char */ if (p == desc) return -EINVAL; return 0; }
/* user_defined.c: user defined key type * * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/user-type.h> #include <linux/uaccess.h> #include "internal.h" static int logon_vet_description(const char *desc); /* * user defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_user = { .name = "user", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; EXPORT_SYMBOL_GPL(key_type_user); /* * This key type is essentially the same as key_type_user, but it does * not define a .read op. This is suitable for storing username and * password pairs in the keyring that you do not want to be readable * from userspace. */ struct key_type key_type_logon = { .name = "logon", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .vet_description = logon_vet_description, }; EXPORT_SYMBOL_GPL(key_type_logon); /* * Preparse a user defined key payload */ int user_preparse(struct key_preparsed_payload *prep) { struct user_key_payload *upayload; size_t datalen = prep->datalen; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) return -ENOMEM; /* attach the data */ prep->quotalen = datalen; prep->payload.data[0] = upayload; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); return 0; } EXPORT_SYMBOL_GPL(user_preparse); /* * Free a preparse of a user defined key payload */ void user_free_preparse(struct key_preparsed_payload *prep) { kzfree(prep->payload.data[0]); } EXPORT_SYMBOL_GPL(user_free_preparse); static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } /* * update a user defined key * - the key's semaphore is write-locked */ int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (key_is_positive(key)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } EXPORT_SYMBOL_GPL(user_update); /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void user_revoke(struct key *key) { struct user_key_payload *upayload = user_key_payload_locked(key); /* clear the quota */ key_payload_reserve(key, 0); if (upayload) { rcu_assign_keypointer(key, NULL); call_rcu(&upayload->rcu, user_free_payload_rcu); } } EXPORT_SYMBOL(user_revoke); /* * dispose of the data dangling from the corpse of a user key */ void user_destroy(struct key *key) { struct user_key_payload *upayload = key->payload.data[0]; kzfree(upayload); } EXPORT_SYMBOL_GPL(user_destroy); /* * describe the user key */ void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_positive(key)) seq_printf(m, ": %u", key->datalen); } EXPORT_SYMBOL_GPL(user_describe); /* * read the key data * - the key's semaphore is read-locked */ long user_read(const struct key *key, char __user *buffer, size_t buflen) { const struct user_key_payload *upayload; long ret; upayload = user_key_payload_locked(key); ret = upayload->datalen; /* we can return the data as is */ if (buffer && buflen > 0) { if (buflen > upayload->datalen) buflen = upayload->datalen; if (copy_to_user(buffer, upayload->data, buflen) != 0) ret = -EFAULT; } return ret; } EXPORT_SYMBOL_GPL(user_read); /* Vet the description for a "logon" key */ static int logon_vet_description(const char *desc) { char *p; /* require a "qualified" description string */ p = strchr(desc, ':'); if (!p) return -EINVAL; /* also reject description with ':' as first char */ if (p == desc) return -EINVAL; return 0; }
void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); }
void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_positive(key)) seq_printf(m, ": %u", key->datalen); }
{'added': [(117, '\tif (key_is_positive(key))'), (165, '\tif (key_is_positive(key))')], 'deleted': [(117, '\tif (!test_bit(KEY_FLAG_NEGATIVE, &key->flags))'), (165, '\tif (key_is_instantiated(key))')]}
2
2
125
699
https://github.com/torvalds/linux
CVE-2017-15951
['CWE-20']
user_defined.c
user_update
/* user_defined.c: user defined key type * * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/user-type.h> #include <linux/uaccess.h> #include "internal.h" static int logon_vet_description(const char *desc); /* * user defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_user = { .name = "user", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; EXPORT_SYMBOL_GPL(key_type_user); /* * This key type is essentially the same as key_type_user, but it does * not define a .read op. This is suitable for storing username and * password pairs in the keyring that you do not want to be readable * from userspace. */ struct key_type key_type_logon = { .name = "logon", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .vet_description = logon_vet_description, }; EXPORT_SYMBOL_GPL(key_type_logon); /* * Preparse a user defined key payload */ int user_preparse(struct key_preparsed_payload *prep) { struct user_key_payload *upayload; size_t datalen = prep->datalen; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) return -ENOMEM; /* attach the data */ prep->quotalen = datalen; prep->payload.data[0] = upayload; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); return 0; } EXPORT_SYMBOL_GPL(user_preparse); /* * Free a preparse of a user defined key payload */ void user_free_preparse(struct key_preparsed_payload *prep) { kzfree(prep->payload.data[0]); } EXPORT_SYMBOL_GPL(user_free_preparse); static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } /* * update a user defined key * - the key's semaphore is write-locked */ int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } EXPORT_SYMBOL_GPL(user_update); /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void user_revoke(struct key *key) { struct user_key_payload *upayload = user_key_payload_locked(key); /* clear the quota */ key_payload_reserve(key, 0); if (upayload) { rcu_assign_keypointer(key, NULL); call_rcu(&upayload->rcu, user_free_payload_rcu); } } EXPORT_SYMBOL(user_revoke); /* * dispose of the data dangling from the corpse of a user key */ void user_destroy(struct key *key) { struct user_key_payload *upayload = key->payload.data[0]; kzfree(upayload); } EXPORT_SYMBOL_GPL(user_destroy); /* * describe the user key */ void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); } EXPORT_SYMBOL_GPL(user_describe); /* * read the key data * - the key's semaphore is read-locked */ long user_read(const struct key *key, char __user *buffer, size_t buflen) { const struct user_key_payload *upayload; long ret; upayload = user_key_payload_locked(key); ret = upayload->datalen; /* we can return the data as is */ if (buffer && buflen > 0) { if (buflen > upayload->datalen) buflen = upayload->datalen; if (copy_to_user(buffer, upayload->data, buflen) != 0) ret = -EFAULT; } return ret; } EXPORT_SYMBOL_GPL(user_read); /* Vet the description for a "logon" key */ static int logon_vet_description(const char *desc) { char *p; /* require a "qualified" description string */ p = strchr(desc, ':'); if (!p) return -EINVAL; /* also reject description with ':' as first char */ if (p == desc) return -EINVAL; return 0; }
/* user_defined.c: user defined key type * * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/user-type.h> #include <linux/uaccess.h> #include "internal.h" static int logon_vet_description(const char *desc); /* * user defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_user = { .name = "user", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; EXPORT_SYMBOL_GPL(key_type_user); /* * This key type is essentially the same as key_type_user, but it does * not define a .read op. This is suitable for storing username and * password pairs in the keyring that you do not want to be readable * from userspace. */ struct key_type key_type_logon = { .name = "logon", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .vet_description = logon_vet_description, }; EXPORT_SYMBOL_GPL(key_type_logon); /* * Preparse a user defined key payload */ int user_preparse(struct key_preparsed_payload *prep) { struct user_key_payload *upayload; size_t datalen = prep->datalen; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) return -ENOMEM; /* attach the data */ prep->quotalen = datalen; prep->payload.data[0] = upayload; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); return 0; } EXPORT_SYMBOL_GPL(user_preparse); /* * Free a preparse of a user defined key payload */ void user_free_preparse(struct key_preparsed_payload *prep) { kzfree(prep->payload.data[0]); } EXPORT_SYMBOL_GPL(user_free_preparse); static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } /* * update a user defined key * - the key's semaphore is write-locked */ int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (key_is_positive(key)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } EXPORT_SYMBOL_GPL(user_update); /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void user_revoke(struct key *key) { struct user_key_payload *upayload = user_key_payload_locked(key); /* clear the quota */ key_payload_reserve(key, 0); if (upayload) { rcu_assign_keypointer(key, NULL); call_rcu(&upayload->rcu, user_free_payload_rcu); } } EXPORT_SYMBOL(user_revoke); /* * dispose of the data dangling from the corpse of a user key */ void user_destroy(struct key *key) { struct user_key_payload *upayload = key->payload.data[0]; kzfree(upayload); } EXPORT_SYMBOL_GPL(user_destroy); /* * describe the user key */ void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_positive(key)) seq_printf(m, ": %u", key->datalen); } EXPORT_SYMBOL_GPL(user_describe); /* * read the key data * - the key's semaphore is read-locked */ long user_read(const struct key *key, char __user *buffer, size_t buflen) { const struct user_key_payload *upayload; long ret; upayload = user_key_payload_locked(key); ret = upayload->datalen; /* we can return the data as is */ if (buffer && buflen > 0) { if (buflen > upayload->datalen) buflen = upayload->datalen; if (copy_to_user(buffer, upayload->data, buflen) != 0) ret = -EFAULT; } return ret; } EXPORT_SYMBOL_GPL(user_read); /* Vet the description for a "logon" key */ static int logon_vet_description(const char *desc) { char *p; /* require a "qualified" description string */ p = strchr(desc, ':'); if (!p) return -EINVAL; /* also reject description with ':' as first char */ if (p == desc) return -EINVAL; return 0; }
int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; }
int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (key_is_positive(key)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; }
{'added': [(117, '\tif (key_is_positive(key))'), (165, '\tif (key_is_positive(key))')], 'deleted': [(117, '\tif (!test_bit(KEY_FLAG_NEGATIVE, &key->flags))'), (165, '\tif (key_is_instantiated(key))')]}
2
2
125
699
https://github.com/torvalds/linux
CVE-2017-15951
['CWE-20']
vboxguest_linux.c
vbg_misc_device_ioctl
/* SPDX-License-Identifier: GPL-2.0 */ /* * vboxguest linux pci driver, char-dev and input-device code, * * Copyright (C) 2006-2016 Oracle Corporation */ #include <linux/input.h> #include <linux/kernel.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/poll.h> #include <linux/vbox_utils.h> #include "vboxguest_core.h" /** The device name. */ #define DEVICE_NAME "vboxguest" /** The device name for the device node open to everyone. */ #define DEVICE_NAME_USER "vboxuser" /** VirtualBox PCI vendor ID. */ #define VBOX_VENDORID 0x80ee /** VMMDev PCI card product ID. */ #define VMMDEV_DEVICEID 0xcafe /** Mutex protecting the global vbg_gdev pointer used by vbg_get/put_gdev. */ static DEFINE_MUTEX(vbg_gdev_mutex); /** Global vbg_gdev pointer used by vbg_get/put_gdev. */ static struct vbg_dev *vbg_gdev; static int vbg_misc_device_open(struct inode *inode, struct file *filp) { struct vbg_session *session; struct vbg_dev *gdev; /* misc_open sets filp->private_data to our misc device */ gdev = container_of(filp->private_data, struct vbg_dev, misc_device); session = vbg_core_open_session(gdev, false); if (IS_ERR(session)) return PTR_ERR(session); filp->private_data = session; return 0; } static int vbg_misc_device_user_open(struct inode *inode, struct file *filp) { struct vbg_session *session; struct vbg_dev *gdev; /* misc_open sets filp->private_data to our misc device */ gdev = container_of(filp->private_data, struct vbg_dev, misc_device_user); session = vbg_core_open_session(gdev, false); if (IS_ERR(session)) return PTR_ERR(session); filp->private_data = session; return 0; } /** * Close device. * Return: 0 on success, negated errno on failure. * @inode: Pointer to inode info structure. * @filp: Associated file pointer. */ static int vbg_misc_device_close(struct inode *inode, struct file *filp) { vbg_core_close_session(filp->private_data); filp->private_data = NULL; return 0; } /** * Device I/O Control entry point. * Return: 0 on success, negated errno on failure. * @filp: Associated file pointer. * @req: The request specified to ioctl(). * @arg: The argument specified to ioctl(). */ static long vbg_misc_device_ioctl(struct file *filp, unsigned int req, unsigned long arg) { struct vbg_session *session = filp->private_data; size_t returned_size, size; struct vbg_ioctl_hdr hdr; bool is_vmmdev_req; int ret = 0; void *buf; if (copy_from_user(&hdr, (void *)arg, sizeof(hdr))) return -EFAULT; if (hdr.version != VBG_IOCTL_HDR_VERSION) return -EINVAL; if (hdr.size_in < sizeof(hdr) || (hdr.size_out && hdr.size_out < sizeof(hdr))) return -EINVAL; size = max(hdr.size_in, hdr.size_out); if (_IOC_SIZE(req) && _IOC_SIZE(req) != size) return -EINVAL; if (size > SZ_16M) return -E2BIG; /* * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid * the need for a bounce-buffer and another copy later on. */ is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) || req == VBG_IOCTL_VMMDEV_REQUEST_BIG; if (is_vmmdev_req) buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT); else buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; if (copy_from_user(buf, (void *)arg, hdr.size_in)) { ret = -EFAULT; goto out; } if (hdr.size_in < size) memset(buf + hdr.size_in, 0, size - hdr.size_in); ret = vbg_core_ioctl(session, req, buf); if (ret) goto out; returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out; if (returned_size > size) { vbg_debug("%s: too much output data %zu > %zu\n", __func__, returned_size, size); returned_size = size; } if (copy_to_user((void *)arg, buf, returned_size) != 0) ret = -EFAULT; out: if (is_vmmdev_req) vbg_req_free(buf, size); else kfree(buf); return ret; } /** The file_operations structures. */ static const struct file_operations vbg_misc_device_fops = { .owner = THIS_MODULE, .open = vbg_misc_device_open, .release = vbg_misc_device_close, .unlocked_ioctl = vbg_misc_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vbg_misc_device_ioctl, #endif }; static const struct file_operations vbg_misc_device_user_fops = { .owner = THIS_MODULE, .open = vbg_misc_device_user_open, .release = vbg_misc_device_close, .unlocked_ioctl = vbg_misc_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vbg_misc_device_ioctl, #endif }; /** * Called when the input device is first opened. * * Sets up absolute mouse reporting. */ static int vbg_input_open(struct input_dev *input) { struct vbg_dev *gdev = input_get_drvdata(input); u32 feat = VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE | VMMDEV_MOUSE_NEW_PROTOCOL; int ret; ret = vbg_core_set_mouse_status(gdev, feat); if (ret) return ret; return 0; } /** * Called if all open handles to the input device are closed. * * Disables absolute reporting. */ static void vbg_input_close(struct input_dev *input) { struct vbg_dev *gdev = input_get_drvdata(input); vbg_core_set_mouse_status(gdev, 0); } /** * Creates the kernel input device. * * Return: 0 on success, negated errno on failure. */ static int vbg_create_input_device(struct vbg_dev *gdev) { struct input_dev *input; input = devm_input_allocate_device(gdev->dev); if (!input) return -ENOMEM; input->id.bustype = BUS_PCI; input->id.vendor = VBOX_VENDORID; input->id.product = VMMDEV_DEVICEID; input->open = vbg_input_open; input->close = vbg_input_close; input->dev.parent = gdev->dev; input->name = "VirtualBox mouse integration"; input_set_abs_params(input, ABS_X, VMMDEV_MOUSE_RANGE_MIN, VMMDEV_MOUSE_RANGE_MAX, 0, 0); input_set_abs_params(input, ABS_Y, VMMDEV_MOUSE_RANGE_MIN, VMMDEV_MOUSE_RANGE_MAX, 0, 0); input_set_capability(input, EV_KEY, BTN_MOUSE); input_set_drvdata(input, gdev); gdev->input = input; return input_register_device(gdev->input); } static ssize_t host_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct vbg_dev *gdev = dev_get_drvdata(dev); return sprintf(buf, "%s\n", gdev->host_version); } static ssize_t host_features_show(struct device *dev, struct device_attribute *attr, char *buf) { struct vbg_dev *gdev = dev_get_drvdata(dev); return sprintf(buf, "%#x\n", gdev->host_features); } static DEVICE_ATTR_RO(host_version); static DEVICE_ATTR_RO(host_features); /** * Does the PCI detection and init of the device. * * Return: 0 on success, negated errno on failure. */ static int vbg_pci_probe(struct pci_dev *pci, const struct pci_device_id *id) { struct device *dev = &pci->dev; resource_size_t io, io_len, mmio, mmio_len; struct vmmdev_memory *vmmdev; struct vbg_dev *gdev; int ret; gdev = devm_kzalloc(dev, sizeof(*gdev), GFP_KERNEL); if (!gdev) return -ENOMEM; ret = pci_enable_device(pci); if (ret != 0) { vbg_err("vboxguest: Error enabling device: %d\n", ret); return ret; } ret = -ENODEV; io = pci_resource_start(pci, 0); io_len = pci_resource_len(pci, 0); if (!io || !io_len) { vbg_err("vboxguest: Error IO-port resource (0) is missing\n"); goto err_disable_pcidev; } if (devm_request_region(dev, io, io_len, DEVICE_NAME) == NULL) { vbg_err("vboxguest: Error could not claim IO resource\n"); ret = -EBUSY; goto err_disable_pcidev; } mmio = pci_resource_start(pci, 1); mmio_len = pci_resource_len(pci, 1); if (!mmio || !mmio_len) { vbg_err("vboxguest: Error MMIO resource (1) is missing\n"); goto err_disable_pcidev; } if (devm_request_mem_region(dev, mmio, mmio_len, DEVICE_NAME) == NULL) { vbg_err("vboxguest: Error could not claim MMIO resource\n"); ret = -EBUSY; goto err_disable_pcidev; } vmmdev = devm_ioremap(dev, mmio, mmio_len); if (!vmmdev) { vbg_err("vboxguest: Error ioremap failed; MMIO addr=%pap size=%pap\n", &mmio, &mmio_len); goto err_disable_pcidev; } /* Validate MMIO region version and size. */ if (vmmdev->version != VMMDEV_MEMORY_VERSION || vmmdev->size < 32 || vmmdev->size > mmio_len) { vbg_err("vboxguest: Bogus VMMDev memory; version=%08x (expected %08x) size=%d (expected <= %d)\n", vmmdev->version, VMMDEV_MEMORY_VERSION, vmmdev->size, (int)mmio_len); goto err_disable_pcidev; } gdev->io_port = io; gdev->mmio = vmmdev; gdev->dev = dev; gdev->misc_device.minor = MISC_DYNAMIC_MINOR; gdev->misc_device.name = DEVICE_NAME; gdev->misc_device.fops = &vbg_misc_device_fops; gdev->misc_device_user.minor = MISC_DYNAMIC_MINOR; gdev->misc_device_user.name = DEVICE_NAME_USER; gdev->misc_device_user.fops = &vbg_misc_device_user_fops; ret = vbg_core_init(gdev, VMMDEV_EVENT_MOUSE_POSITION_CHANGED); if (ret) goto err_disable_pcidev; ret = vbg_create_input_device(gdev); if (ret) { vbg_err("vboxguest: Error creating input device: %d\n", ret); goto err_vbg_core_exit; } ret = devm_request_irq(dev, pci->irq, vbg_core_isr, IRQF_SHARED, DEVICE_NAME, gdev); if (ret) { vbg_err("vboxguest: Error requesting irq: %d\n", ret); goto err_vbg_core_exit; } ret = misc_register(&gdev->misc_device); if (ret) { vbg_err("vboxguest: Error misc_register %s failed: %d\n", DEVICE_NAME, ret); goto err_vbg_core_exit; } ret = misc_register(&gdev->misc_device_user); if (ret) { vbg_err("vboxguest: Error misc_register %s failed: %d\n", DEVICE_NAME_USER, ret); goto err_unregister_misc_device; } mutex_lock(&vbg_gdev_mutex); if (!vbg_gdev) vbg_gdev = gdev; else ret = -EBUSY; mutex_unlock(&vbg_gdev_mutex); if (ret) { vbg_err("vboxguest: Error more then 1 vbox guest pci device\n"); goto err_unregister_misc_device_user; } pci_set_drvdata(pci, gdev); device_create_file(dev, &dev_attr_host_version); device_create_file(dev, &dev_attr_host_features); vbg_info("vboxguest: misc device minor %d, IRQ %d, I/O port %x, MMIO at %pap (size %pap)\n", gdev->misc_device.minor, pci->irq, gdev->io_port, &mmio, &mmio_len); return 0; err_unregister_misc_device_user: misc_deregister(&gdev->misc_device_user); err_unregister_misc_device: misc_deregister(&gdev->misc_device); err_vbg_core_exit: vbg_core_exit(gdev); err_disable_pcidev: pci_disable_device(pci); return ret; } static void vbg_pci_remove(struct pci_dev *pci) { struct vbg_dev *gdev = pci_get_drvdata(pci); mutex_lock(&vbg_gdev_mutex); vbg_gdev = NULL; mutex_unlock(&vbg_gdev_mutex); device_remove_file(gdev->dev, &dev_attr_host_features); device_remove_file(gdev->dev, &dev_attr_host_version); misc_deregister(&gdev->misc_device_user); misc_deregister(&gdev->misc_device); vbg_core_exit(gdev); pci_disable_device(pci); } struct vbg_dev *vbg_get_gdev(void) { mutex_lock(&vbg_gdev_mutex); /* * Note on success we keep the mutex locked until vbg_put_gdev(), * this stops vbg_pci_remove from removing the device from underneath * vboxsf. vboxsf will only hold a reference for a short while. */ if (vbg_gdev) return vbg_gdev; mutex_unlock(&vbg_gdev_mutex); return ERR_PTR(-ENODEV); } EXPORT_SYMBOL(vbg_get_gdev); void vbg_put_gdev(struct vbg_dev *gdev) { WARN_ON(gdev != vbg_gdev); mutex_unlock(&vbg_gdev_mutex); } EXPORT_SYMBOL(vbg_put_gdev); /** * Callback for mouse events. * * This is called at the end of the ISR, after leaving the event spinlock, if * VMMDEV_EVENT_MOUSE_POSITION_CHANGED was raised by the host. * * @gdev: The device extension. */ void vbg_linux_mouse_event(struct vbg_dev *gdev) { int rc; /* Report events to the kernel input device */ gdev->mouse_status_req->mouse_features = 0; gdev->mouse_status_req->pointer_pos_x = 0; gdev->mouse_status_req->pointer_pos_y = 0; rc = vbg_req_perform(gdev, gdev->mouse_status_req); if (rc >= 0) { input_report_abs(gdev->input, ABS_X, gdev->mouse_status_req->pointer_pos_x); input_report_abs(gdev->input, ABS_Y, gdev->mouse_status_req->pointer_pos_y); input_sync(gdev->input); } } static const struct pci_device_id vbg_pci_ids[] = { { .vendor = VBOX_VENDORID, .device = VMMDEV_DEVICEID }, {} }; MODULE_DEVICE_TABLE(pci, vbg_pci_ids); static struct pci_driver vbg_pci_driver = { .name = DEVICE_NAME, .id_table = vbg_pci_ids, .probe = vbg_pci_probe, .remove = vbg_pci_remove, }; module_pci_driver(vbg_pci_driver); MODULE_AUTHOR("Oracle Corporation"); MODULE_DESCRIPTION("Oracle VM VirtualBox Guest Additions for Linux Module"); MODULE_LICENSE("GPL");
/* SPDX-License-Identifier: GPL-2.0 */ /* * vboxguest linux pci driver, char-dev and input-device code, * * Copyright (C) 2006-2016 Oracle Corporation */ #include <linux/input.h> #include <linux/kernel.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/poll.h> #include <linux/vbox_utils.h> #include "vboxguest_core.h" /** The device name. */ #define DEVICE_NAME "vboxguest" /** The device name for the device node open to everyone. */ #define DEVICE_NAME_USER "vboxuser" /** VirtualBox PCI vendor ID. */ #define VBOX_VENDORID 0x80ee /** VMMDev PCI card product ID. */ #define VMMDEV_DEVICEID 0xcafe /** Mutex protecting the global vbg_gdev pointer used by vbg_get/put_gdev. */ static DEFINE_MUTEX(vbg_gdev_mutex); /** Global vbg_gdev pointer used by vbg_get/put_gdev. */ static struct vbg_dev *vbg_gdev; static int vbg_misc_device_open(struct inode *inode, struct file *filp) { struct vbg_session *session; struct vbg_dev *gdev; /* misc_open sets filp->private_data to our misc device */ gdev = container_of(filp->private_data, struct vbg_dev, misc_device); session = vbg_core_open_session(gdev, false); if (IS_ERR(session)) return PTR_ERR(session); filp->private_data = session; return 0; } static int vbg_misc_device_user_open(struct inode *inode, struct file *filp) { struct vbg_session *session; struct vbg_dev *gdev; /* misc_open sets filp->private_data to our misc device */ gdev = container_of(filp->private_data, struct vbg_dev, misc_device_user); session = vbg_core_open_session(gdev, false); if (IS_ERR(session)) return PTR_ERR(session); filp->private_data = session; return 0; } /** * Close device. * Return: 0 on success, negated errno on failure. * @inode: Pointer to inode info structure. * @filp: Associated file pointer. */ static int vbg_misc_device_close(struct inode *inode, struct file *filp) { vbg_core_close_session(filp->private_data); filp->private_data = NULL; return 0; } /** * Device I/O Control entry point. * Return: 0 on success, negated errno on failure. * @filp: Associated file pointer. * @req: The request specified to ioctl(). * @arg: The argument specified to ioctl(). */ static long vbg_misc_device_ioctl(struct file *filp, unsigned int req, unsigned long arg) { struct vbg_session *session = filp->private_data; size_t returned_size, size; struct vbg_ioctl_hdr hdr; bool is_vmmdev_req; int ret = 0; void *buf; if (copy_from_user(&hdr, (void *)arg, sizeof(hdr))) return -EFAULT; if (hdr.version != VBG_IOCTL_HDR_VERSION) return -EINVAL; if (hdr.size_in < sizeof(hdr) || (hdr.size_out && hdr.size_out < sizeof(hdr))) return -EINVAL; size = max(hdr.size_in, hdr.size_out); if (_IOC_SIZE(req) && _IOC_SIZE(req) != size) return -EINVAL; if (size > SZ_16M) return -E2BIG; /* * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid * the need for a bounce-buffer and another copy later on. */ is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) || req == VBG_IOCTL_VMMDEV_REQUEST_BIG; if (is_vmmdev_req) buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT); else buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; *((struct vbg_ioctl_hdr *)buf) = hdr; if (copy_from_user(buf + sizeof(hdr), (void *)arg + sizeof(hdr), hdr.size_in - sizeof(hdr))) { ret = -EFAULT; goto out; } if (hdr.size_in < size) memset(buf + hdr.size_in, 0, size - hdr.size_in); ret = vbg_core_ioctl(session, req, buf); if (ret) goto out; returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out; if (returned_size > size) { vbg_debug("%s: too much output data %zu > %zu\n", __func__, returned_size, size); returned_size = size; } if (copy_to_user((void *)arg, buf, returned_size) != 0) ret = -EFAULT; out: if (is_vmmdev_req) vbg_req_free(buf, size); else kfree(buf); return ret; } /** The file_operations structures. */ static const struct file_operations vbg_misc_device_fops = { .owner = THIS_MODULE, .open = vbg_misc_device_open, .release = vbg_misc_device_close, .unlocked_ioctl = vbg_misc_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vbg_misc_device_ioctl, #endif }; static const struct file_operations vbg_misc_device_user_fops = { .owner = THIS_MODULE, .open = vbg_misc_device_user_open, .release = vbg_misc_device_close, .unlocked_ioctl = vbg_misc_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vbg_misc_device_ioctl, #endif }; /** * Called when the input device is first opened. * * Sets up absolute mouse reporting. */ static int vbg_input_open(struct input_dev *input) { struct vbg_dev *gdev = input_get_drvdata(input); u32 feat = VMMDEV_MOUSE_GUEST_CAN_ABSOLUTE | VMMDEV_MOUSE_NEW_PROTOCOL; int ret; ret = vbg_core_set_mouse_status(gdev, feat); if (ret) return ret; return 0; } /** * Called if all open handles to the input device are closed. * * Disables absolute reporting. */ static void vbg_input_close(struct input_dev *input) { struct vbg_dev *gdev = input_get_drvdata(input); vbg_core_set_mouse_status(gdev, 0); } /** * Creates the kernel input device. * * Return: 0 on success, negated errno on failure. */ static int vbg_create_input_device(struct vbg_dev *gdev) { struct input_dev *input; input = devm_input_allocate_device(gdev->dev); if (!input) return -ENOMEM; input->id.bustype = BUS_PCI; input->id.vendor = VBOX_VENDORID; input->id.product = VMMDEV_DEVICEID; input->open = vbg_input_open; input->close = vbg_input_close; input->dev.parent = gdev->dev; input->name = "VirtualBox mouse integration"; input_set_abs_params(input, ABS_X, VMMDEV_MOUSE_RANGE_MIN, VMMDEV_MOUSE_RANGE_MAX, 0, 0); input_set_abs_params(input, ABS_Y, VMMDEV_MOUSE_RANGE_MIN, VMMDEV_MOUSE_RANGE_MAX, 0, 0); input_set_capability(input, EV_KEY, BTN_MOUSE); input_set_drvdata(input, gdev); gdev->input = input; return input_register_device(gdev->input); } static ssize_t host_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct vbg_dev *gdev = dev_get_drvdata(dev); return sprintf(buf, "%s\n", gdev->host_version); } static ssize_t host_features_show(struct device *dev, struct device_attribute *attr, char *buf) { struct vbg_dev *gdev = dev_get_drvdata(dev); return sprintf(buf, "%#x\n", gdev->host_features); } static DEVICE_ATTR_RO(host_version); static DEVICE_ATTR_RO(host_features); /** * Does the PCI detection and init of the device. * * Return: 0 on success, negated errno on failure. */ static int vbg_pci_probe(struct pci_dev *pci, const struct pci_device_id *id) { struct device *dev = &pci->dev; resource_size_t io, io_len, mmio, mmio_len; struct vmmdev_memory *vmmdev; struct vbg_dev *gdev; int ret; gdev = devm_kzalloc(dev, sizeof(*gdev), GFP_KERNEL); if (!gdev) return -ENOMEM; ret = pci_enable_device(pci); if (ret != 0) { vbg_err("vboxguest: Error enabling device: %d\n", ret); return ret; } ret = -ENODEV; io = pci_resource_start(pci, 0); io_len = pci_resource_len(pci, 0); if (!io || !io_len) { vbg_err("vboxguest: Error IO-port resource (0) is missing\n"); goto err_disable_pcidev; } if (devm_request_region(dev, io, io_len, DEVICE_NAME) == NULL) { vbg_err("vboxguest: Error could not claim IO resource\n"); ret = -EBUSY; goto err_disable_pcidev; } mmio = pci_resource_start(pci, 1); mmio_len = pci_resource_len(pci, 1); if (!mmio || !mmio_len) { vbg_err("vboxguest: Error MMIO resource (1) is missing\n"); goto err_disable_pcidev; } if (devm_request_mem_region(dev, mmio, mmio_len, DEVICE_NAME) == NULL) { vbg_err("vboxguest: Error could not claim MMIO resource\n"); ret = -EBUSY; goto err_disable_pcidev; } vmmdev = devm_ioremap(dev, mmio, mmio_len); if (!vmmdev) { vbg_err("vboxguest: Error ioremap failed; MMIO addr=%pap size=%pap\n", &mmio, &mmio_len); goto err_disable_pcidev; } /* Validate MMIO region version and size. */ if (vmmdev->version != VMMDEV_MEMORY_VERSION || vmmdev->size < 32 || vmmdev->size > mmio_len) { vbg_err("vboxguest: Bogus VMMDev memory; version=%08x (expected %08x) size=%d (expected <= %d)\n", vmmdev->version, VMMDEV_MEMORY_VERSION, vmmdev->size, (int)mmio_len); goto err_disable_pcidev; } gdev->io_port = io; gdev->mmio = vmmdev; gdev->dev = dev; gdev->misc_device.minor = MISC_DYNAMIC_MINOR; gdev->misc_device.name = DEVICE_NAME; gdev->misc_device.fops = &vbg_misc_device_fops; gdev->misc_device_user.minor = MISC_DYNAMIC_MINOR; gdev->misc_device_user.name = DEVICE_NAME_USER; gdev->misc_device_user.fops = &vbg_misc_device_user_fops; ret = vbg_core_init(gdev, VMMDEV_EVENT_MOUSE_POSITION_CHANGED); if (ret) goto err_disable_pcidev; ret = vbg_create_input_device(gdev); if (ret) { vbg_err("vboxguest: Error creating input device: %d\n", ret); goto err_vbg_core_exit; } ret = devm_request_irq(dev, pci->irq, vbg_core_isr, IRQF_SHARED, DEVICE_NAME, gdev); if (ret) { vbg_err("vboxguest: Error requesting irq: %d\n", ret); goto err_vbg_core_exit; } ret = misc_register(&gdev->misc_device); if (ret) { vbg_err("vboxguest: Error misc_register %s failed: %d\n", DEVICE_NAME, ret); goto err_vbg_core_exit; } ret = misc_register(&gdev->misc_device_user); if (ret) { vbg_err("vboxguest: Error misc_register %s failed: %d\n", DEVICE_NAME_USER, ret); goto err_unregister_misc_device; } mutex_lock(&vbg_gdev_mutex); if (!vbg_gdev) vbg_gdev = gdev; else ret = -EBUSY; mutex_unlock(&vbg_gdev_mutex); if (ret) { vbg_err("vboxguest: Error more then 1 vbox guest pci device\n"); goto err_unregister_misc_device_user; } pci_set_drvdata(pci, gdev); device_create_file(dev, &dev_attr_host_version); device_create_file(dev, &dev_attr_host_features); vbg_info("vboxguest: misc device minor %d, IRQ %d, I/O port %x, MMIO at %pap (size %pap)\n", gdev->misc_device.minor, pci->irq, gdev->io_port, &mmio, &mmio_len); return 0; err_unregister_misc_device_user: misc_deregister(&gdev->misc_device_user); err_unregister_misc_device: misc_deregister(&gdev->misc_device); err_vbg_core_exit: vbg_core_exit(gdev); err_disable_pcidev: pci_disable_device(pci); return ret; } static void vbg_pci_remove(struct pci_dev *pci) { struct vbg_dev *gdev = pci_get_drvdata(pci); mutex_lock(&vbg_gdev_mutex); vbg_gdev = NULL; mutex_unlock(&vbg_gdev_mutex); device_remove_file(gdev->dev, &dev_attr_host_features); device_remove_file(gdev->dev, &dev_attr_host_version); misc_deregister(&gdev->misc_device_user); misc_deregister(&gdev->misc_device); vbg_core_exit(gdev); pci_disable_device(pci); } struct vbg_dev *vbg_get_gdev(void) { mutex_lock(&vbg_gdev_mutex); /* * Note on success we keep the mutex locked until vbg_put_gdev(), * this stops vbg_pci_remove from removing the device from underneath * vboxsf. vboxsf will only hold a reference for a short while. */ if (vbg_gdev) return vbg_gdev; mutex_unlock(&vbg_gdev_mutex); return ERR_PTR(-ENODEV); } EXPORT_SYMBOL(vbg_get_gdev); void vbg_put_gdev(struct vbg_dev *gdev) { WARN_ON(gdev != vbg_gdev); mutex_unlock(&vbg_gdev_mutex); } EXPORT_SYMBOL(vbg_put_gdev); /** * Callback for mouse events. * * This is called at the end of the ISR, after leaving the event spinlock, if * VMMDEV_EVENT_MOUSE_POSITION_CHANGED was raised by the host. * * @gdev: The device extension. */ void vbg_linux_mouse_event(struct vbg_dev *gdev) { int rc; /* Report events to the kernel input device */ gdev->mouse_status_req->mouse_features = 0; gdev->mouse_status_req->pointer_pos_x = 0; gdev->mouse_status_req->pointer_pos_y = 0; rc = vbg_req_perform(gdev, gdev->mouse_status_req); if (rc >= 0) { input_report_abs(gdev->input, ABS_X, gdev->mouse_status_req->pointer_pos_x); input_report_abs(gdev->input, ABS_Y, gdev->mouse_status_req->pointer_pos_y); input_sync(gdev->input); } } static const struct pci_device_id vbg_pci_ids[] = { { .vendor = VBOX_VENDORID, .device = VMMDEV_DEVICEID }, {} }; MODULE_DEVICE_TABLE(pci, vbg_pci_ids); static struct pci_driver vbg_pci_driver = { .name = DEVICE_NAME, .id_table = vbg_pci_ids, .probe = vbg_pci_probe, .remove = vbg_pci_remove, }; module_pci_driver(vbg_pci_driver); MODULE_AUTHOR("Oracle Corporation"); MODULE_DESCRIPTION("Oracle VM VirtualBox Guest Additions for Linux Module"); MODULE_LICENSE("GPL");
static long vbg_misc_device_ioctl(struct file *filp, unsigned int req, unsigned long arg) { struct vbg_session *session = filp->private_data; size_t returned_size, size; struct vbg_ioctl_hdr hdr; bool is_vmmdev_req; int ret = 0; void *buf; if (copy_from_user(&hdr, (void *)arg, sizeof(hdr))) return -EFAULT; if (hdr.version != VBG_IOCTL_HDR_VERSION) return -EINVAL; if (hdr.size_in < sizeof(hdr) || (hdr.size_out && hdr.size_out < sizeof(hdr))) return -EINVAL; size = max(hdr.size_in, hdr.size_out); if (_IOC_SIZE(req) && _IOC_SIZE(req) != size) return -EINVAL; if (size > SZ_16M) return -E2BIG; /* * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid * the need for a bounce-buffer and another copy later on. */ is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) || req == VBG_IOCTL_VMMDEV_REQUEST_BIG; if (is_vmmdev_req) buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT); else buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; if (copy_from_user(buf, (void *)arg, hdr.size_in)) { ret = -EFAULT; goto out; } if (hdr.size_in < size) memset(buf + hdr.size_in, 0, size - hdr.size_in); ret = vbg_core_ioctl(session, req, buf); if (ret) goto out; returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out; if (returned_size > size) { vbg_debug("%s: too much output data %zu > %zu\n", __func__, returned_size, size); returned_size = size; } if (copy_to_user((void *)arg, buf, returned_size) != 0) ret = -EFAULT; out: if (is_vmmdev_req) vbg_req_free(buf, size); else kfree(buf); return ret; }
static long vbg_misc_device_ioctl(struct file *filp, unsigned int req, unsigned long arg) { struct vbg_session *session = filp->private_data; size_t returned_size, size; struct vbg_ioctl_hdr hdr; bool is_vmmdev_req; int ret = 0; void *buf; if (copy_from_user(&hdr, (void *)arg, sizeof(hdr))) return -EFAULT; if (hdr.version != VBG_IOCTL_HDR_VERSION) return -EINVAL; if (hdr.size_in < sizeof(hdr) || (hdr.size_out && hdr.size_out < sizeof(hdr))) return -EINVAL; size = max(hdr.size_in, hdr.size_out); if (_IOC_SIZE(req) && _IOC_SIZE(req) != size) return -EINVAL; if (size > SZ_16M) return -E2BIG; /* * IOCTL_VMMDEV_REQUEST needs the buffer to be below 4G to avoid * the need for a bounce-buffer and another copy later on. */ is_vmmdev_req = (req & ~IOCSIZE_MASK) == VBG_IOCTL_VMMDEV_REQUEST(0) || req == VBG_IOCTL_VMMDEV_REQUEST_BIG; if (is_vmmdev_req) buf = vbg_req_alloc(size, VBG_IOCTL_HDR_TYPE_DEFAULT); else buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; *((struct vbg_ioctl_hdr *)buf) = hdr; if (copy_from_user(buf + sizeof(hdr), (void *)arg + sizeof(hdr), hdr.size_in - sizeof(hdr))) { ret = -EFAULT; goto out; } if (hdr.size_in < size) memset(buf + hdr.size_in, 0, size - hdr.size_in); ret = vbg_core_ioctl(session, req, buf); if (ret) goto out; returned_size = ((struct vbg_ioctl_hdr *)buf)->size_out; if (returned_size > size) { vbg_debug("%s: too much output data %zu > %zu\n", __func__, returned_size, size); returned_size = size; } if (copy_to_user((void *)arg, buf, returned_size) != 0) ret = -EFAULT; out: if (is_vmmdev_req) vbg_req_free(buf, size); else kfree(buf); return ret; }
{'added': [(124, '\t*((struct vbg_ioctl_hdr *)buf) = hdr;'), (125, '\tif (copy_from_user(buf + sizeof(hdr), (void *)arg + sizeof(hdr),'), (126, '\t\t\t hdr.size_in - sizeof(hdr))) {')], 'deleted': [(124, '\tif (copy_from_user(buf, (void *)arg, hdr.size_in)) {')]}
3
1
330
1,934
https://github.com/torvalds/linux
CVE-2018-12633
['CWE-362']
skcipher.c
crypto_skcipher_init_tfm
/* * Symmetric key cipher operations. * * Generic encrypt/decrypt wrapper for ciphers, handles operations across * multiple page boundaries by using temporary blocks. In user context, * the kernel is given a chance to schedule us once per page. * * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/aead.h> #include <crypto/internal/skcipher.h> #include <crypto/scatterwalk.h> #include <linux/bug.h> #include <linux/cryptouser.h> #include <linux/compiler.h> #include <linux/list.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/seq_file.h> #include <net/netlink.h> #include "internal.h" enum { SKCIPHER_WALK_PHYS = 1 << 0, SKCIPHER_WALK_SLOW = 1 << 1, SKCIPHER_WALK_COPY = 1 << 2, SKCIPHER_WALK_DIFF = 1 << 3, SKCIPHER_WALK_SLEEP = 1 << 4, }; struct skcipher_walk_buffer { struct list_head entry; struct scatter_walk dst; unsigned int len; u8 *data; u8 buffer[]; }; static int skcipher_walk_next(struct skcipher_walk *walk); static inline void skcipher_unmap(struct scatter_walk *walk, void *vaddr) { if (PageHighMem(scatterwalk_page(walk))) kunmap_atomic(vaddr); } static inline void *skcipher_map(struct scatter_walk *walk) { struct page *page = scatterwalk_page(walk); return (PageHighMem(page) ? kmap_atomic(page) : page_address(page)) + offset_in_page(walk->offset); } static inline void skcipher_map_src(struct skcipher_walk *walk) { walk->src.virt.addr = skcipher_map(&walk->in); } static inline void skcipher_map_dst(struct skcipher_walk *walk) { walk->dst.virt.addr = skcipher_map(&walk->out); } static inline void skcipher_unmap_src(struct skcipher_walk *walk) { skcipher_unmap(&walk->in, walk->src.virt.addr); } static inline void skcipher_unmap_dst(struct skcipher_walk *walk) { skcipher_unmap(&walk->out, walk->dst.virt.addr); } static inline gfp_t skcipher_walk_gfp(struct skcipher_walk *walk) { return walk->flags & SKCIPHER_WALK_SLEEP ? GFP_KERNEL : GFP_ATOMIC; } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *skcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static int skcipher_done_slow(struct skcipher_walk *walk, unsigned int bsize) { u8 *addr; addr = (u8 *)ALIGN((unsigned long)walk->buffer, walk->alignmask + 1); addr = skcipher_get_spot(addr, bsize); scatterwalk_copychunks(addr, &walk->out, bsize, (walk->flags & SKCIPHER_WALK_PHYS) ? 2 : 1); return 0; } int skcipher_walk_done(struct skcipher_walk *walk, int err) { unsigned int n = walk->nbytes - err; unsigned int nbytes; nbytes = walk->total - n; if (unlikely(err < 0)) { nbytes = 0; n = 0; } else if (likely(!(walk->flags & (SKCIPHER_WALK_PHYS | SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY | SKCIPHER_WALK_DIFF)))) { unmap_src: skcipher_unmap_src(walk); } else if (walk->flags & SKCIPHER_WALK_DIFF) { skcipher_unmap_dst(walk); goto unmap_src; } else if (walk->flags & SKCIPHER_WALK_COPY) { skcipher_map_dst(walk); memcpy(walk->dst.virt.addr, walk->page, n); skcipher_unmap_dst(walk); } else if (unlikely(walk->flags & SKCIPHER_WALK_SLOW)) { if (WARN_ON(err)) { err = -EINVAL; nbytes = 0; } else n = skcipher_done_slow(walk, n); } if (err > 0) err = 0; walk->total = nbytes; walk->nbytes = nbytes; scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); if (nbytes) { crypto_yield(walk->flags & SKCIPHER_WALK_SLEEP ? CRYPTO_TFM_REQ_MAY_SLEEP : 0); return skcipher_walk_next(walk); } /* Short-circuit for the common/fast path. */ if (!((unsigned long)walk->buffer | (unsigned long)walk->page)) goto out; if (walk->flags & SKCIPHER_WALK_PHYS) goto out; if (walk->iv != walk->oiv) memcpy(walk->oiv, walk->iv, walk->ivsize); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); out: return err; } EXPORT_SYMBOL_GPL(skcipher_walk_done); void skcipher_walk_complete(struct skcipher_walk *walk, int err) { struct skcipher_walk_buffer *p, *tmp; list_for_each_entry_safe(p, tmp, &walk->buffers, entry) { u8 *data; if (err) goto done; data = p->data; if (!data) { data = PTR_ALIGN(&p->buffer[0], walk->alignmask + 1); data = skcipher_get_spot(data, walk->stride); } scatterwalk_copychunks(data, &p->dst, p->len, 1); if (offset_in_page(p->data) + p->len + walk->stride > PAGE_SIZE) free_page((unsigned long)p->data); done: list_del(&p->entry); kfree(p); } if (!err && walk->iv != walk->oiv) memcpy(walk->oiv, walk->iv, walk->ivsize); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); } EXPORT_SYMBOL_GPL(skcipher_walk_complete); static void skcipher_queue_write(struct skcipher_walk *walk, struct skcipher_walk_buffer *p) { p->dst = walk->out; list_add_tail(&p->entry, &walk->buffers); } static int skcipher_next_slow(struct skcipher_walk *walk, unsigned int bsize) { bool phys = walk->flags & SKCIPHER_WALK_PHYS; unsigned alignmask = walk->alignmask; struct skcipher_walk_buffer *p; unsigned a; unsigned n; u8 *buffer; void *v; if (!phys) { if (!walk->buffer) walk->buffer = walk->page; buffer = walk->buffer; if (buffer) goto ok; } /* Start with the minimum alignment of kmalloc. */ a = crypto_tfm_ctx_alignment() - 1; n = bsize; if (phys) { /* Calculate the minimum alignment of p->buffer. */ a &= (sizeof(*p) ^ (sizeof(*p) - 1)) >> 1; n += sizeof(*p); } /* Minimum size to align p->buffer by alignmask. */ n += alignmask & ~a; /* Minimum size to ensure p->buffer does not straddle a page. */ n += (bsize - 1) & ~(alignmask | a); v = kzalloc(n, skcipher_walk_gfp(walk)); if (!v) return skcipher_walk_done(walk, -ENOMEM); if (phys) { p = v; p->len = bsize; skcipher_queue_write(walk, p); buffer = p->buffer; } else { walk->buffer = v; buffer = v; } ok: walk->dst.virt.addr = PTR_ALIGN(buffer, alignmask + 1); walk->dst.virt.addr = skcipher_get_spot(walk->dst.virt.addr, bsize); walk->src.virt.addr = walk->dst.virt.addr; scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0); walk->nbytes = bsize; walk->flags |= SKCIPHER_WALK_SLOW; return 0; } static int skcipher_next_copy(struct skcipher_walk *walk) { struct skcipher_walk_buffer *p; u8 *tmp = walk->page; skcipher_map_src(walk); memcpy(tmp, walk->src.virt.addr, walk->nbytes); skcipher_unmap_src(walk); walk->src.virt.addr = tmp; walk->dst.virt.addr = tmp; if (!(walk->flags & SKCIPHER_WALK_PHYS)) return 0; p = kmalloc(sizeof(*p), skcipher_walk_gfp(walk)); if (!p) return -ENOMEM; p->data = walk->page; p->len = walk->nbytes; skcipher_queue_write(walk, p); if (offset_in_page(walk->page) + walk->nbytes + walk->stride > PAGE_SIZE) walk->page = NULL; else walk->page += walk->nbytes; return 0; } static int skcipher_next_fast(struct skcipher_walk *walk) { unsigned long diff; walk->src.phys.page = scatterwalk_page(&walk->in); walk->src.phys.offset = offset_in_page(walk->in.offset); walk->dst.phys.page = scatterwalk_page(&walk->out); walk->dst.phys.offset = offset_in_page(walk->out.offset); if (walk->flags & SKCIPHER_WALK_PHYS) return 0; diff = walk->src.phys.offset - walk->dst.phys.offset; diff |= walk->src.virt.page - walk->dst.virt.page; skcipher_map_src(walk); walk->dst.virt.addr = walk->src.virt.addr; if (diff) { walk->flags |= SKCIPHER_WALK_DIFF; skcipher_map_dst(walk); } return 0; } static int skcipher_walk_next(struct skcipher_walk *walk) { unsigned int bsize; unsigned int n; int err; walk->flags &= ~(SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY | SKCIPHER_WALK_DIFF); n = walk->total; bsize = min(walk->stride, max(n, walk->blocksize)); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (unlikely(n < bsize)) { if (unlikely(walk->total < walk->blocksize)) return skcipher_walk_done(walk, -EINVAL); slow_path: err = skcipher_next_slow(walk, bsize); goto set_phys_lowmem; } if (unlikely((walk->in.offset | walk->out.offset) & walk->alignmask)) { if (!walk->page) { gfp_t gfp = skcipher_walk_gfp(walk); walk->page = (void *)__get_free_page(gfp); if (!walk->page) goto slow_path; } walk->nbytes = min_t(unsigned, n, PAGE_SIZE - offset_in_page(walk->page)); walk->flags |= SKCIPHER_WALK_COPY; err = skcipher_next_copy(walk); goto set_phys_lowmem; } walk->nbytes = n; return skcipher_next_fast(walk); set_phys_lowmem: if (!err && (walk->flags & SKCIPHER_WALK_PHYS)) { walk->src.phys.page = virt_to_page(walk->src.virt.addr); walk->dst.phys.page = virt_to_page(walk->dst.virt.addr); walk->src.phys.offset &= PAGE_SIZE - 1; walk->dst.phys.offset &= PAGE_SIZE - 1; } return err; } EXPORT_SYMBOL_GPL(skcipher_walk_next); static int skcipher_copy_iv(struct skcipher_walk *walk) { unsigned a = crypto_tfm_ctx_alignment() - 1; unsigned alignmask = walk->alignmask; unsigned ivsize = walk->ivsize; unsigned bs = walk->stride; unsigned aligned_bs; unsigned size; u8 *iv; aligned_bs = ALIGN(bs, alignmask); /* Minimum size to align buffer by alignmask. */ size = alignmask & ~a; if (walk->flags & SKCIPHER_WALK_PHYS) size += ivsize; else { size += aligned_bs + ivsize; /* Minimum size to ensure buffer does not straddle a page. */ size += (bs - 1) & ~(alignmask | a); } walk->buffer = kmalloc(size, skcipher_walk_gfp(walk)); if (!walk->buffer) return -ENOMEM; iv = PTR_ALIGN(walk->buffer, alignmask + 1); iv = skcipher_get_spot(iv, bs) + aligned_bs; walk->iv = memcpy(iv, walk->iv, walk->ivsize); return 0; } static int skcipher_walk_first(struct skcipher_walk *walk) { walk->nbytes = 0; if (WARN_ON_ONCE(in_irq())) return -EDEADLK; if (unlikely(!walk->total)) return 0; walk->buffer = NULL; if (unlikely(((unsigned long)walk->iv & walk->alignmask))) { int err = skcipher_copy_iv(walk); if (err) return err; } walk->page = NULL; walk->nbytes = walk->total; return skcipher_walk_next(walk); } static int skcipher_walk_skcipher(struct skcipher_walk *walk, struct skcipher_request *req) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); scatterwalk_start(&walk->in, req->src); scatterwalk_start(&walk->out, req->dst); walk->total = req->cryptlen; walk->iv = req->iv; walk->oiv = req->iv; walk->flags &= ~SKCIPHER_WALK_SLEEP; walk->flags |= req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ? SKCIPHER_WALK_SLEEP : 0; walk->blocksize = crypto_skcipher_blocksize(tfm); walk->stride = crypto_skcipher_walksize(tfm); walk->ivsize = crypto_skcipher_ivsize(tfm); walk->alignmask = crypto_skcipher_alignmask(tfm); return skcipher_walk_first(walk); } int skcipher_walk_virt(struct skcipher_walk *walk, struct skcipher_request *req, bool atomic) { int err; walk->flags &= ~SKCIPHER_WALK_PHYS; err = skcipher_walk_skcipher(walk, req); walk->flags &= atomic ? ~SKCIPHER_WALK_SLEEP : ~0; return err; } EXPORT_SYMBOL_GPL(skcipher_walk_virt); void skcipher_walk_atomise(struct skcipher_walk *walk) { walk->flags &= ~SKCIPHER_WALK_SLEEP; } EXPORT_SYMBOL_GPL(skcipher_walk_atomise); int skcipher_walk_async(struct skcipher_walk *walk, struct skcipher_request *req) { walk->flags |= SKCIPHER_WALK_PHYS; INIT_LIST_HEAD(&walk->buffers); return skcipher_walk_skcipher(walk, req); } EXPORT_SYMBOL_GPL(skcipher_walk_async); static int skcipher_walk_aead_common(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { struct crypto_aead *tfm = crypto_aead_reqtfm(req); int err; walk->flags &= ~SKCIPHER_WALK_PHYS; scatterwalk_start(&walk->in, req->src); scatterwalk_start(&walk->out, req->dst); scatterwalk_copychunks(NULL, &walk->in, req->assoclen, 2); scatterwalk_copychunks(NULL, &walk->out, req->assoclen, 2); walk->iv = req->iv; walk->oiv = req->iv; if (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) walk->flags |= SKCIPHER_WALK_SLEEP; else walk->flags &= ~SKCIPHER_WALK_SLEEP; walk->blocksize = crypto_aead_blocksize(tfm); walk->stride = crypto_aead_chunksize(tfm); walk->ivsize = crypto_aead_ivsize(tfm); walk->alignmask = crypto_aead_alignmask(tfm); err = skcipher_walk_first(walk); if (atomic) walk->flags &= ~SKCIPHER_WALK_SLEEP; return err; } int skcipher_walk_aead(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { walk->total = req->cryptlen; return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead); int skcipher_walk_aead_encrypt(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { walk->total = req->cryptlen; return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead_encrypt); int skcipher_walk_aead_decrypt(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { struct crypto_aead *tfm = crypto_aead_reqtfm(req); walk->total = req->cryptlen - crypto_aead_authsize(tfm); return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead_decrypt); static unsigned int crypto_skcipher_extsize(struct crypto_alg *alg) { if (alg->cra_type == &crypto_blkcipher_type) return sizeof(struct crypto_blkcipher *); if (alg->cra_type == &crypto_ablkcipher_type || alg->cra_type == &crypto_givcipher_type) return sizeof(struct crypto_ablkcipher *); return crypto_alg_extsize(alg); } static int skcipher_setkey_blkcipher(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm); struct crypto_blkcipher *blkcipher = *ctx; int err; crypto_blkcipher_clear_flags(blkcipher, ~0); crypto_blkcipher_set_flags(blkcipher, crypto_skcipher_get_flags(tfm) & CRYPTO_TFM_REQ_MASK); err = crypto_blkcipher_setkey(blkcipher, key, keylen); crypto_skcipher_set_flags(tfm, crypto_blkcipher_get_flags(blkcipher) & CRYPTO_TFM_RES_MASK); return err; } static int skcipher_crypt_blkcipher(struct skcipher_request *req, int (*crypt)(struct blkcipher_desc *, struct scatterlist *, struct scatterlist *, unsigned int)) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm); struct blkcipher_desc desc = { .tfm = *ctx, .info = req->iv, .flags = req->base.flags, }; return crypt(&desc, req->dst, req->src, req->cryptlen); } static int skcipher_encrypt_blkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; return skcipher_crypt_blkcipher(req, alg->encrypt); } static int skcipher_decrypt_blkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; return skcipher_crypt_blkcipher(req, alg->decrypt); } static void crypto_exit_skcipher_ops_blkcipher(struct crypto_tfm *tfm) { struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm); crypto_free_blkcipher(*ctx); } static int crypto_init_skcipher_ops_blkcipher(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm); struct crypto_blkcipher *blkcipher; struct crypto_tfm *btfm; if (!crypto_mod_get(calg)) return -EAGAIN; btfm = __crypto_alloc_tfm(calg, CRYPTO_ALG_TYPE_BLKCIPHER, CRYPTO_ALG_TYPE_MASK); if (IS_ERR(btfm)) { crypto_mod_put(calg); return PTR_ERR(btfm); } blkcipher = __crypto_blkcipher_cast(btfm); *ctx = blkcipher; tfm->exit = crypto_exit_skcipher_ops_blkcipher; skcipher->setkey = skcipher_setkey_blkcipher; skcipher->encrypt = skcipher_encrypt_blkcipher; skcipher->decrypt = skcipher_decrypt_blkcipher; skcipher->ivsize = crypto_blkcipher_ivsize(blkcipher); skcipher->keysize = calg->cra_blkcipher.max_keysize; return 0; } static int skcipher_setkey_ablkcipher(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm); struct crypto_ablkcipher *ablkcipher = *ctx; int err; crypto_ablkcipher_clear_flags(ablkcipher, ~0); crypto_ablkcipher_set_flags(ablkcipher, crypto_skcipher_get_flags(tfm) & CRYPTO_TFM_REQ_MASK); err = crypto_ablkcipher_setkey(ablkcipher, key, keylen); crypto_skcipher_set_flags(tfm, crypto_ablkcipher_get_flags(ablkcipher) & CRYPTO_TFM_RES_MASK); return err; } static int skcipher_crypt_ablkcipher(struct skcipher_request *req, int (*crypt)(struct ablkcipher_request *)) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm); struct ablkcipher_request *subreq = skcipher_request_ctx(req); ablkcipher_request_set_tfm(subreq, *ctx); ablkcipher_request_set_callback(subreq, skcipher_request_flags(req), req->base.complete, req->base.data); ablkcipher_request_set_crypt(subreq, req->src, req->dst, req->cryptlen, req->iv); return crypt(subreq); } static int skcipher_encrypt_ablkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; return skcipher_crypt_ablkcipher(req, alg->encrypt); } static int skcipher_decrypt_ablkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; return skcipher_crypt_ablkcipher(req, alg->decrypt); } static void crypto_exit_skcipher_ops_ablkcipher(struct crypto_tfm *tfm) { struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm); crypto_free_ablkcipher(*ctx); } static int crypto_init_skcipher_ops_ablkcipher(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm); struct crypto_ablkcipher *ablkcipher; struct crypto_tfm *abtfm; if (!crypto_mod_get(calg)) return -EAGAIN; abtfm = __crypto_alloc_tfm(calg, 0, 0); if (IS_ERR(abtfm)) { crypto_mod_put(calg); return PTR_ERR(abtfm); } ablkcipher = __crypto_ablkcipher_cast(abtfm); *ctx = ablkcipher; tfm->exit = crypto_exit_skcipher_ops_ablkcipher; skcipher->setkey = skcipher_setkey_ablkcipher; skcipher->encrypt = skcipher_encrypt_ablkcipher; skcipher->decrypt = skcipher_decrypt_ablkcipher; skcipher->ivsize = crypto_ablkcipher_ivsize(ablkcipher); skcipher->reqsize = crypto_ablkcipher_reqsize(ablkcipher) + sizeof(struct ablkcipher_request); skcipher->keysize = calg->cra_ablkcipher.max_keysize; return 0; } static void crypto_skcipher_exit_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); alg->exit(skcipher); } static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = alg->setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; } static void crypto_skcipher_free_instance(struct crypto_instance *inst) { struct skcipher_instance *skcipher = container_of(inst, struct skcipher_instance, s.base); skcipher->free(skcipher); } static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg) __maybe_unused; static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg, base); seq_printf(m, "type : skcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", skcipher->min_keysize); seq_printf(m, "max keysize : %u\n", skcipher->max_keysize); seq_printf(m, "ivsize : %u\n", skcipher->ivsize); seq_printf(m, "chunksize : %u\n", skcipher->chunksize); seq_printf(m, "walksize : %u\n", skcipher->walksize); } #ifdef CONFIG_NET static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg, base); strncpy(rblkcipher.type, "skcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, "<none>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = skcipher->min_keysize; rblkcipher.max_keysize = skcipher->max_keysize; rblkcipher.ivsize = skcipher->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static const struct crypto_type crypto_skcipher_type2 = { .extsize = crypto_skcipher_extsize, .init_tfm = crypto_skcipher_init_tfm, .free = crypto_skcipher_free_instance, #ifdef CONFIG_PROC_FS .show = crypto_skcipher_show, #endif .report = crypto_skcipher_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_BLKCIPHER_MASK, .type = CRYPTO_ALG_TYPE_SKCIPHER, .tfmsize = offsetof(struct crypto_skcipher, base), }; int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { spawn->base.frontend = &crypto_skcipher_type2; return crypto_grab_spawn(&spawn->base, name, type, mask); } EXPORT_SYMBOL_GPL(crypto_grab_skcipher); struct crypto_skcipher *crypto_alloc_skcipher(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_skcipher_type2, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_skcipher); int crypto_has_skcipher2(const char *alg_name, u32 type, u32 mask) { return crypto_type_has_alg(alg_name, &crypto_skcipher_type2, type, mask); } EXPORT_SYMBOL_GPL(crypto_has_skcipher2); static int skcipher_prepare_alg(struct skcipher_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->ivsize > PAGE_SIZE / 8 || alg->chunksize > PAGE_SIZE / 8 || alg->walksize > PAGE_SIZE / 8) return -EINVAL; if (!alg->chunksize) alg->chunksize = base->cra_blocksize; if (!alg->walksize) alg->walksize = alg->chunksize; base->cra_type = &crypto_skcipher_type2; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SKCIPHER; return 0; } int crypto_register_skcipher(struct skcipher_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = skcipher_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_skcipher); void crypto_unregister_skcipher(struct skcipher_alg *alg) { crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_skcipher); int crypto_register_skciphers(struct skcipher_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_skcipher(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_skcipher(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_skciphers); void crypto_unregister_skciphers(struct skcipher_alg *algs, int count) { int i; for (i = count - 1; i >= 0; --i) crypto_unregister_skcipher(&algs[i]); } EXPORT_SYMBOL_GPL(crypto_unregister_skciphers); int skcipher_register_instance(struct crypto_template *tmpl, struct skcipher_instance *inst) { int err; err = skcipher_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, skcipher_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(skcipher_register_instance); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Symmetric key cipher type");
/* * Symmetric key cipher operations. * * Generic encrypt/decrypt wrapper for ciphers, handles operations across * multiple page boundaries by using temporary blocks. In user context, * the kernel is given a chance to schedule us once per page. * * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/aead.h> #include <crypto/internal/skcipher.h> #include <crypto/scatterwalk.h> #include <linux/bug.h> #include <linux/cryptouser.h> #include <linux/compiler.h> #include <linux/list.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/seq_file.h> #include <net/netlink.h> #include "internal.h" enum { SKCIPHER_WALK_PHYS = 1 << 0, SKCIPHER_WALK_SLOW = 1 << 1, SKCIPHER_WALK_COPY = 1 << 2, SKCIPHER_WALK_DIFF = 1 << 3, SKCIPHER_WALK_SLEEP = 1 << 4, }; struct skcipher_walk_buffer { struct list_head entry; struct scatter_walk dst; unsigned int len; u8 *data; u8 buffer[]; }; static int skcipher_walk_next(struct skcipher_walk *walk); static inline void skcipher_unmap(struct scatter_walk *walk, void *vaddr) { if (PageHighMem(scatterwalk_page(walk))) kunmap_atomic(vaddr); } static inline void *skcipher_map(struct scatter_walk *walk) { struct page *page = scatterwalk_page(walk); return (PageHighMem(page) ? kmap_atomic(page) : page_address(page)) + offset_in_page(walk->offset); } static inline void skcipher_map_src(struct skcipher_walk *walk) { walk->src.virt.addr = skcipher_map(&walk->in); } static inline void skcipher_map_dst(struct skcipher_walk *walk) { walk->dst.virt.addr = skcipher_map(&walk->out); } static inline void skcipher_unmap_src(struct skcipher_walk *walk) { skcipher_unmap(&walk->in, walk->src.virt.addr); } static inline void skcipher_unmap_dst(struct skcipher_walk *walk) { skcipher_unmap(&walk->out, walk->dst.virt.addr); } static inline gfp_t skcipher_walk_gfp(struct skcipher_walk *walk) { return walk->flags & SKCIPHER_WALK_SLEEP ? GFP_KERNEL : GFP_ATOMIC; } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *skcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static int skcipher_done_slow(struct skcipher_walk *walk, unsigned int bsize) { u8 *addr; addr = (u8 *)ALIGN((unsigned long)walk->buffer, walk->alignmask + 1); addr = skcipher_get_spot(addr, bsize); scatterwalk_copychunks(addr, &walk->out, bsize, (walk->flags & SKCIPHER_WALK_PHYS) ? 2 : 1); return 0; } int skcipher_walk_done(struct skcipher_walk *walk, int err) { unsigned int n = walk->nbytes - err; unsigned int nbytes; nbytes = walk->total - n; if (unlikely(err < 0)) { nbytes = 0; n = 0; } else if (likely(!(walk->flags & (SKCIPHER_WALK_PHYS | SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY | SKCIPHER_WALK_DIFF)))) { unmap_src: skcipher_unmap_src(walk); } else if (walk->flags & SKCIPHER_WALK_DIFF) { skcipher_unmap_dst(walk); goto unmap_src; } else if (walk->flags & SKCIPHER_WALK_COPY) { skcipher_map_dst(walk); memcpy(walk->dst.virt.addr, walk->page, n); skcipher_unmap_dst(walk); } else if (unlikely(walk->flags & SKCIPHER_WALK_SLOW)) { if (WARN_ON(err)) { err = -EINVAL; nbytes = 0; } else n = skcipher_done_slow(walk, n); } if (err > 0) err = 0; walk->total = nbytes; walk->nbytes = nbytes; scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); if (nbytes) { crypto_yield(walk->flags & SKCIPHER_WALK_SLEEP ? CRYPTO_TFM_REQ_MAY_SLEEP : 0); return skcipher_walk_next(walk); } /* Short-circuit for the common/fast path. */ if (!((unsigned long)walk->buffer | (unsigned long)walk->page)) goto out; if (walk->flags & SKCIPHER_WALK_PHYS) goto out; if (walk->iv != walk->oiv) memcpy(walk->oiv, walk->iv, walk->ivsize); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); out: return err; } EXPORT_SYMBOL_GPL(skcipher_walk_done); void skcipher_walk_complete(struct skcipher_walk *walk, int err) { struct skcipher_walk_buffer *p, *tmp; list_for_each_entry_safe(p, tmp, &walk->buffers, entry) { u8 *data; if (err) goto done; data = p->data; if (!data) { data = PTR_ALIGN(&p->buffer[0], walk->alignmask + 1); data = skcipher_get_spot(data, walk->stride); } scatterwalk_copychunks(data, &p->dst, p->len, 1); if (offset_in_page(p->data) + p->len + walk->stride > PAGE_SIZE) free_page((unsigned long)p->data); done: list_del(&p->entry); kfree(p); } if (!err && walk->iv != walk->oiv) memcpy(walk->oiv, walk->iv, walk->ivsize); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); } EXPORT_SYMBOL_GPL(skcipher_walk_complete); static void skcipher_queue_write(struct skcipher_walk *walk, struct skcipher_walk_buffer *p) { p->dst = walk->out; list_add_tail(&p->entry, &walk->buffers); } static int skcipher_next_slow(struct skcipher_walk *walk, unsigned int bsize) { bool phys = walk->flags & SKCIPHER_WALK_PHYS; unsigned alignmask = walk->alignmask; struct skcipher_walk_buffer *p; unsigned a; unsigned n; u8 *buffer; void *v; if (!phys) { if (!walk->buffer) walk->buffer = walk->page; buffer = walk->buffer; if (buffer) goto ok; } /* Start with the minimum alignment of kmalloc. */ a = crypto_tfm_ctx_alignment() - 1; n = bsize; if (phys) { /* Calculate the minimum alignment of p->buffer. */ a &= (sizeof(*p) ^ (sizeof(*p) - 1)) >> 1; n += sizeof(*p); } /* Minimum size to align p->buffer by alignmask. */ n += alignmask & ~a; /* Minimum size to ensure p->buffer does not straddle a page. */ n += (bsize - 1) & ~(alignmask | a); v = kzalloc(n, skcipher_walk_gfp(walk)); if (!v) return skcipher_walk_done(walk, -ENOMEM); if (phys) { p = v; p->len = bsize; skcipher_queue_write(walk, p); buffer = p->buffer; } else { walk->buffer = v; buffer = v; } ok: walk->dst.virt.addr = PTR_ALIGN(buffer, alignmask + 1); walk->dst.virt.addr = skcipher_get_spot(walk->dst.virt.addr, bsize); walk->src.virt.addr = walk->dst.virt.addr; scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0); walk->nbytes = bsize; walk->flags |= SKCIPHER_WALK_SLOW; return 0; } static int skcipher_next_copy(struct skcipher_walk *walk) { struct skcipher_walk_buffer *p; u8 *tmp = walk->page; skcipher_map_src(walk); memcpy(tmp, walk->src.virt.addr, walk->nbytes); skcipher_unmap_src(walk); walk->src.virt.addr = tmp; walk->dst.virt.addr = tmp; if (!(walk->flags & SKCIPHER_WALK_PHYS)) return 0; p = kmalloc(sizeof(*p), skcipher_walk_gfp(walk)); if (!p) return -ENOMEM; p->data = walk->page; p->len = walk->nbytes; skcipher_queue_write(walk, p); if (offset_in_page(walk->page) + walk->nbytes + walk->stride > PAGE_SIZE) walk->page = NULL; else walk->page += walk->nbytes; return 0; } static int skcipher_next_fast(struct skcipher_walk *walk) { unsigned long diff; walk->src.phys.page = scatterwalk_page(&walk->in); walk->src.phys.offset = offset_in_page(walk->in.offset); walk->dst.phys.page = scatterwalk_page(&walk->out); walk->dst.phys.offset = offset_in_page(walk->out.offset); if (walk->flags & SKCIPHER_WALK_PHYS) return 0; diff = walk->src.phys.offset - walk->dst.phys.offset; diff |= walk->src.virt.page - walk->dst.virt.page; skcipher_map_src(walk); walk->dst.virt.addr = walk->src.virt.addr; if (diff) { walk->flags |= SKCIPHER_WALK_DIFF; skcipher_map_dst(walk); } return 0; } static int skcipher_walk_next(struct skcipher_walk *walk) { unsigned int bsize; unsigned int n; int err; walk->flags &= ~(SKCIPHER_WALK_SLOW | SKCIPHER_WALK_COPY | SKCIPHER_WALK_DIFF); n = walk->total; bsize = min(walk->stride, max(n, walk->blocksize)); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (unlikely(n < bsize)) { if (unlikely(walk->total < walk->blocksize)) return skcipher_walk_done(walk, -EINVAL); slow_path: err = skcipher_next_slow(walk, bsize); goto set_phys_lowmem; } if (unlikely((walk->in.offset | walk->out.offset) & walk->alignmask)) { if (!walk->page) { gfp_t gfp = skcipher_walk_gfp(walk); walk->page = (void *)__get_free_page(gfp); if (!walk->page) goto slow_path; } walk->nbytes = min_t(unsigned, n, PAGE_SIZE - offset_in_page(walk->page)); walk->flags |= SKCIPHER_WALK_COPY; err = skcipher_next_copy(walk); goto set_phys_lowmem; } walk->nbytes = n; return skcipher_next_fast(walk); set_phys_lowmem: if (!err && (walk->flags & SKCIPHER_WALK_PHYS)) { walk->src.phys.page = virt_to_page(walk->src.virt.addr); walk->dst.phys.page = virt_to_page(walk->dst.virt.addr); walk->src.phys.offset &= PAGE_SIZE - 1; walk->dst.phys.offset &= PAGE_SIZE - 1; } return err; } EXPORT_SYMBOL_GPL(skcipher_walk_next); static int skcipher_copy_iv(struct skcipher_walk *walk) { unsigned a = crypto_tfm_ctx_alignment() - 1; unsigned alignmask = walk->alignmask; unsigned ivsize = walk->ivsize; unsigned bs = walk->stride; unsigned aligned_bs; unsigned size; u8 *iv; aligned_bs = ALIGN(bs, alignmask); /* Minimum size to align buffer by alignmask. */ size = alignmask & ~a; if (walk->flags & SKCIPHER_WALK_PHYS) size += ivsize; else { size += aligned_bs + ivsize; /* Minimum size to ensure buffer does not straddle a page. */ size += (bs - 1) & ~(alignmask | a); } walk->buffer = kmalloc(size, skcipher_walk_gfp(walk)); if (!walk->buffer) return -ENOMEM; iv = PTR_ALIGN(walk->buffer, alignmask + 1); iv = skcipher_get_spot(iv, bs) + aligned_bs; walk->iv = memcpy(iv, walk->iv, walk->ivsize); return 0; } static int skcipher_walk_first(struct skcipher_walk *walk) { walk->nbytes = 0; if (WARN_ON_ONCE(in_irq())) return -EDEADLK; if (unlikely(!walk->total)) return 0; walk->buffer = NULL; if (unlikely(((unsigned long)walk->iv & walk->alignmask))) { int err = skcipher_copy_iv(walk); if (err) return err; } walk->page = NULL; walk->nbytes = walk->total; return skcipher_walk_next(walk); } static int skcipher_walk_skcipher(struct skcipher_walk *walk, struct skcipher_request *req) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); scatterwalk_start(&walk->in, req->src); scatterwalk_start(&walk->out, req->dst); walk->total = req->cryptlen; walk->iv = req->iv; walk->oiv = req->iv; walk->flags &= ~SKCIPHER_WALK_SLEEP; walk->flags |= req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ? SKCIPHER_WALK_SLEEP : 0; walk->blocksize = crypto_skcipher_blocksize(tfm); walk->stride = crypto_skcipher_walksize(tfm); walk->ivsize = crypto_skcipher_ivsize(tfm); walk->alignmask = crypto_skcipher_alignmask(tfm); return skcipher_walk_first(walk); } int skcipher_walk_virt(struct skcipher_walk *walk, struct skcipher_request *req, bool atomic) { int err; walk->flags &= ~SKCIPHER_WALK_PHYS; err = skcipher_walk_skcipher(walk, req); walk->flags &= atomic ? ~SKCIPHER_WALK_SLEEP : ~0; return err; } EXPORT_SYMBOL_GPL(skcipher_walk_virt); void skcipher_walk_atomise(struct skcipher_walk *walk) { walk->flags &= ~SKCIPHER_WALK_SLEEP; } EXPORT_SYMBOL_GPL(skcipher_walk_atomise); int skcipher_walk_async(struct skcipher_walk *walk, struct skcipher_request *req) { walk->flags |= SKCIPHER_WALK_PHYS; INIT_LIST_HEAD(&walk->buffers); return skcipher_walk_skcipher(walk, req); } EXPORT_SYMBOL_GPL(skcipher_walk_async); static int skcipher_walk_aead_common(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { struct crypto_aead *tfm = crypto_aead_reqtfm(req); int err; walk->flags &= ~SKCIPHER_WALK_PHYS; scatterwalk_start(&walk->in, req->src); scatterwalk_start(&walk->out, req->dst); scatterwalk_copychunks(NULL, &walk->in, req->assoclen, 2); scatterwalk_copychunks(NULL, &walk->out, req->assoclen, 2); walk->iv = req->iv; walk->oiv = req->iv; if (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) walk->flags |= SKCIPHER_WALK_SLEEP; else walk->flags &= ~SKCIPHER_WALK_SLEEP; walk->blocksize = crypto_aead_blocksize(tfm); walk->stride = crypto_aead_chunksize(tfm); walk->ivsize = crypto_aead_ivsize(tfm); walk->alignmask = crypto_aead_alignmask(tfm); err = skcipher_walk_first(walk); if (atomic) walk->flags &= ~SKCIPHER_WALK_SLEEP; return err; } int skcipher_walk_aead(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { walk->total = req->cryptlen; return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead); int skcipher_walk_aead_encrypt(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { walk->total = req->cryptlen; return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead_encrypt); int skcipher_walk_aead_decrypt(struct skcipher_walk *walk, struct aead_request *req, bool atomic) { struct crypto_aead *tfm = crypto_aead_reqtfm(req); walk->total = req->cryptlen - crypto_aead_authsize(tfm); return skcipher_walk_aead_common(walk, req, atomic); } EXPORT_SYMBOL_GPL(skcipher_walk_aead_decrypt); static unsigned int crypto_skcipher_extsize(struct crypto_alg *alg) { if (alg->cra_type == &crypto_blkcipher_type) return sizeof(struct crypto_blkcipher *); if (alg->cra_type == &crypto_ablkcipher_type || alg->cra_type == &crypto_givcipher_type) return sizeof(struct crypto_ablkcipher *); return crypto_alg_extsize(alg); } static int skcipher_setkey_blkcipher(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm); struct crypto_blkcipher *blkcipher = *ctx; int err; crypto_blkcipher_clear_flags(blkcipher, ~0); crypto_blkcipher_set_flags(blkcipher, crypto_skcipher_get_flags(tfm) & CRYPTO_TFM_REQ_MASK); err = crypto_blkcipher_setkey(blkcipher, key, keylen); crypto_skcipher_set_flags(tfm, crypto_blkcipher_get_flags(blkcipher) & CRYPTO_TFM_RES_MASK); return err; } static int skcipher_crypt_blkcipher(struct skcipher_request *req, int (*crypt)(struct blkcipher_desc *, struct scatterlist *, struct scatterlist *, unsigned int)) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); struct crypto_blkcipher **ctx = crypto_skcipher_ctx(tfm); struct blkcipher_desc desc = { .tfm = *ctx, .info = req->iv, .flags = req->base.flags, }; return crypt(&desc, req->dst, req->src, req->cryptlen); } static int skcipher_encrypt_blkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; return skcipher_crypt_blkcipher(req, alg->encrypt); } static int skcipher_decrypt_blkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; return skcipher_crypt_blkcipher(req, alg->decrypt); } static void crypto_exit_skcipher_ops_blkcipher(struct crypto_tfm *tfm) { struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm); crypto_free_blkcipher(*ctx); } static int crypto_init_skcipher_ops_blkcipher(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct crypto_blkcipher **ctx = crypto_tfm_ctx(tfm); struct crypto_blkcipher *blkcipher; struct crypto_tfm *btfm; if (!crypto_mod_get(calg)) return -EAGAIN; btfm = __crypto_alloc_tfm(calg, CRYPTO_ALG_TYPE_BLKCIPHER, CRYPTO_ALG_TYPE_MASK); if (IS_ERR(btfm)) { crypto_mod_put(calg); return PTR_ERR(btfm); } blkcipher = __crypto_blkcipher_cast(btfm); *ctx = blkcipher; tfm->exit = crypto_exit_skcipher_ops_blkcipher; skcipher->setkey = skcipher_setkey_blkcipher; skcipher->encrypt = skcipher_encrypt_blkcipher; skcipher->decrypt = skcipher_decrypt_blkcipher; skcipher->ivsize = crypto_blkcipher_ivsize(blkcipher); skcipher->keysize = calg->cra_blkcipher.max_keysize; return 0; } static int skcipher_setkey_ablkcipher(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm); struct crypto_ablkcipher *ablkcipher = *ctx; int err; crypto_ablkcipher_clear_flags(ablkcipher, ~0); crypto_ablkcipher_set_flags(ablkcipher, crypto_skcipher_get_flags(tfm) & CRYPTO_TFM_REQ_MASK); err = crypto_ablkcipher_setkey(ablkcipher, key, keylen); crypto_skcipher_set_flags(tfm, crypto_ablkcipher_get_flags(ablkcipher) & CRYPTO_TFM_RES_MASK); return err; } static int skcipher_crypt_ablkcipher(struct skcipher_request *req, int (*crypt)(struct ablkcipher_request *)) { struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req); struct crypto_ablkcipher **ctx = crypto_skcipher_ctx(tfm); struct ablkcipher_request *subreq = skcipher_request_ctx(req); ablkcipher_request_set_tfm(subreq, *ctx); ablkcipher_request_set_callback(subreq, skcipher_request_flags(req), req->base.complete, req->base.data); ablkcipher_request_set_crypt(subreq, req->src, req->dst, req->cryptlen, req->iv); return crypt(subreq); } static int skcipher_encrypt_ablkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; return skcipher_crypt_ablkcipher(req, alg->encrypt); } static int skcipher_decrypt_ablkcipher(struct skcipher_request *req) { struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req); struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher); struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; return skcipher_crypt_ablkcipher(req, alg->decrypt); } static void crypto_exit_skcipher_ops_ablkcipher(struct crypto_tfm *tfm) { struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm); crypto_free_ablkcipher(*ctx); } static int crypto_init_skcipher_ops_ablkcipher(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct crypto_ablkcipher **ctx = crypto_tfm_ctx(tfm); struct crypto_ablkcipher *ablkcipher; struct crypto_tfm *abtfm; if (!crypto_mod_get(calg)) return -EAGAIN; abtfm = __crypto_alloc_tfm(calg, 0, 0); if (IS_ERR(abtfm)) { crypto_mod_put(calg); return PTR_ERR(abtfm); } ablkcipher = __crypto_ablkcipher_cast(abtfm); *ctx = ablkcipher; tfm->exit = crypto_exit_skcipher_ops_ablkcipher; skcipher->setkey = skcipher_setkey_ablkcipher; skcipher->encrypt = skcipher_encrypt_ablkcipher; skcipher->decrypt = skcipher_decrypt_ablkcipher; skcipher->ivsize = crypto_ablkcipher_ivsize(ablkcipher); skcipher->reqsize = crypto_ablkcipher_reqsize(ablkcipher) + sizeof(struct ablkcipher_request); skcipher->keysize = calg->cra_ablkcipher.max_keysize; return 0; } static int skcipher_setkey_unaligned(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { unsigned long alignmask = crypto_skcipher_alignmask(tfm); struct skcipher_alg *cipher = crypto_skcipher_alg(tfm); u8 *buffer, *alignbuffer; unsigned long absize; int ret; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = cipher->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return ret; } static int skcipher_setkey(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen) { struct skcipher_alg *cipher = crypto_skcipher_alg(tfm); unsigned long alignmask = crypto_skcipher_alignmask(tfm); if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) { crypto_skcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN); return -EINVAL; } if ((unsigned long)key & alignmask) return skcipher_setkey_unaligned(tfm, key, keylen); return cipher->setkey(tfm, key, keylen); } static void crypto_skcipher_exit_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); alg->exit(skcipher); } static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = skcipher_setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; } static void crypto_skcipher_free_instance(struct crypto_instance *inst) { struct skcipher_instance *skcipher = container_of(inst, struct skcipher_instance, s.base); skcipher->free(skcipher); } static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg) __maybe_unused; static void crypto_skcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg, base); seq_printf(m, "type : skcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", skcipher->min_keysize); seq_printf(m, "max keysize : %u\n", skcipher->max_keysize); seq_printf(m, "ivsize : %u\n", skcipher->ivsize); seq_printf(m, "chunksize : %u\n", skcipher->chunksize); seq_printf(m, "walksize : %u\n", skcipher->walksize); } #ifdef CONFIG_NET static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; struct skcipher_alg *skcipher = container_of(alg, struct skcipher_alg, base); strncpy(rblkcipher.type, "skcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, "<none>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = skcipher->min_keysize; rblkcipher.max_keysize = skcipher->max_keysize; rblkcipher.ivsize = skcipher->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_skcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static const struct crypto_type crypto_skcipher_type2 = { .extsize = crypto_skcipher_extsize, .init_tfm = crypto_skcipher_init_tfm, .free = crypto_skcipher_free_instance, #ifdef CONFIG_PROC_FS .show = crypto_skcipher_show, #endif .report = crypto_skcipher_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_BLKCIPHER_MASK, .type = CRYPTO_ALG_TYPE_SKCIPHER, .tfmsize = offsetof(struct crypto_skcipher, base), }; int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { spawn->base.frontend = &crypto_skcipher_type2; return crypto_grab_spawn(&spawn->base, name, type, mask); } EXPORT_SYMBOL_GPL(crypto_grab_skcipher); struct crypto_skcipher *crypto_alloc_skcipher(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_skcipher_type2, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_skcipher); int crypto_has_skcipher2(const char *alg_name, u32 type, u32 mask) { return crypto_type_has_alg(alg_name, &crypto_skcipher_type2, type, mask); } EXPORT_SYMBOL_GPL(crypto_has_skcipher2); static int skcipher_prepare_alg(struct skcipher_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->ivsize > PAGE_SIZE / 8 || alg->chunksize > PAGE_SIZE / 8 || alg->walksize > PAGE_SIZE / 8) return -EINVAL; if (!alg->chunksize) alg->chunksize = base->cra_blocksize; if (!alg->walksize) alg->walksize = alg->chunksize; base->cra_type = &crypto_skcipher_type2; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SKCIPHER; return 0; } int crypto_register_skcipher(struct skcipher_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = skcipher_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_skcipher); void crypto_unregister_skcipher(struct skcipher_alg *alg) { crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_skcipher); int crypto_register_skciphers(struct skcipher_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_skcipher(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_skcipher(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_skciphers); void crypto_unregister_skciphers(struct skcipher_alg *algs, int count) { int i; for (i = count - 1; i >= 0; --i) crypto_unregister_skcipher(&algs[i]); } EXPORT_SYMBOL_GPL(crypto_unregister_skciphers); int skcipher_register_instance(struct crypto_template *tmpl, struct skcipher_instance *inst) { int err; err = skcipher_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, skcipher_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(skcipher_register_instance); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Symmetric key cipher type");
static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = alg->setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }
static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = skcipher_setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }
{'added': [(767, 'static int skcipher_setkey_unaligned(struct crypto_skcipher *tfm,'), (768, '\t\t\t\t const u8 *key, unsigned int keylen)'), (769, '{'), (770, '\tunsigned long alignmask = crypto_skcipher_alignmask(tfm);'), (771, '\tstruct skcipher_alg *cipher = crypto_skcipher_alg(tfm);'), (772, '\tu8 *buffer, *alignbuffer;'), (773, '\tunsigned long absize;'), (774, '\tint ret;'), (775, ''), (776, '\tabsize = keylen + alignmask;'), (777, '\tbuffer = kmalloc(absize, GFP_ATOMIC);'), (778, '\tif (!buffer)'), (779, '\t\treturn -ENOMEM;'), (780, ''), (781, '\talignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1);'), (782, '\tmemcpy(alignbuffer, key, keylen);'), (783, '\tret = cipher->setkey(tfm, alignbuffer, keylen);'), (784, '\tkzfree(buffer);'), (785, '\treturn ret;'), (786, '}'), (787, ''), (788, 'static int skcipher_setkey(struct crypto_skcipher *tfm, const u8 *key,'), (789, '\t\t\t unsigned int keylen)'), (790, '{'), (791, '\tstruct skcipher_alg *cipher = crypto_skcipher_alg(tfm);'), (792, '\tunsigned long alignmask = crypto_skcipher_alignmask(tfm);'), (793, ''), (794, '\tif (keylen < cipher->min_keysize || keylen > cipher->max_keysize) {'), (795, '\t\tcrypto_skcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);'), (796, '\t\treturn -EINVAL;'), (797, '\t}'), (798, ''), (799, '\tif ((unsigned long)key & alignmask)'), (800, '\t\treturn skcipher_setkey_unaligned(tfm, key, keylen);'), (801, ''), (802, '\treturn cipher->setkey(tfm, key, keylen);'), (803, '}'), (804, ''), (825, '\tskcipher->setkey = skcipher_setkey;')], 'deleted': [(787, '\tskcipher->setkey = alg->setkey;')]}
39
1
773
5,209
https://github.com/torvalds/linux
CVE-2017-9211
['CWE-476']
idn2.c
main
/* idn2.c - command line interface to libidn2 Copyright (C) 2011-2017 Simon Josefsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <locale.h> #include <unistd.h> #include <idn2.h> #include <unitypes.h> #include <uniconv.h> #include <unistr.h> #include <unistring/localcharset.h> /* Gnulib headers. */ #include "error.h" #include "gettext.h" #define _(String) dgettext (PACKAGE, String) #include "progname.h" #include "version-etc.h" #include "idn2_cmd.h" #include "blurbs.h" #ifdef __cplusplus extern // define a global const variable in C++, C doesn't need it. #endif const char version_etc_copyright[] = /* Do *not* mark this string for translation. %s is a copyright symbol suitable for this locale, and %d is the copyright year. */ "Copyright %s %d Simon Josefsson."; static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); } static void hexdump (const char *prefix, const char *str) { uint8_t *u8; uint32_t *u32 = NULL; size_t u32len; size_t i; const char *encoding = locale_charset (); u8 = u8_strconv_from_encoding (str, encoding, iconveh_error); if (u8) u32 = u8_to_u32 (u8, strlen ((char *) u8), NULL, &u32len); for (i = 0; i < strlen (str); i++) fprintf (stderr, "%s[%lu] = 0x%02x\n", prefix, (unsigned long) i, (unsigned) (str[i] & 0xFF)); if (u8 && strcmp (str, (char *) u8) != 0) for (i = 0; i < strlen ((char *) u8); i++) fprintf (stderr, "UTF-8 %s[%lu] = 0x%02x\n", prefix, (unsigned long) i, u8[i] & 0xFF); if (u8 && u32) for (i = 0; i < u32len; i++) fprintf (stderr, "UCS-4 %s[%lu] = U+%04x\n", prefix, (unsigned long) i, u32[i]); } static struct gengetopt_args_info args_info; static void process_input (char *readbuf, int flags) { size_t len = strlen (readbuf); char *output; const char *tag; int rc; if (len && readbuf[len - 1] == '\n') readbuf[len - 1] = '\0'; if (strcmp (readbuf, "show w") == 0) { puts (WARRANTY); return; } else if (strcmp (readbuf, "show c") == 0) { puts (CONDITIONS); return; } if (args_info.debug_given) hexdump ("input", readbuf); if (args_info.register_given) { rc = idn2_register_ul(readbuf, NULL, &output, flags); tag = "register"; } else if (args_info.decode_given) { rc = idn2_to_unicode_lzlz (readbuf, &output, 0); tag = "decode"; } else { rc = idn2_to_ascii_lz (readbuf, &output, flags); tag = "toAscii"; } if (rc == IDN2_OK) { if (args_info.debug_given) hexdump ("output", readbuf); printf ("%s\n", output); free (output); } else error (EXIT_FAILURE, 0, "%s: %s", tag, idn2_strerror (rc)); } int main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
/* idn2.c - command line interface to libidn2 Copyright (C) 2011-2019 Simon Josefsson, Tim Ruehsen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <locale.h> #include <unistd.h> #include <idn2.h> #include <unitypes.h> #include <uniconv.h> #include <unistr.h> #include <unistring/localcharset.h> /* Gnulib headers. */ #include "error.h" #include "gettext.h" #define _(String) dgettext (PACKAGE, String) #include "progname.h" #include "version-etc.h" #include "idn2_cmd.h" #include "blurbs.h" #ifdef __cplusplus extern // define a global const variable in C++, C doesn't need it. #endif const char version_etc_copyright[] = /* Do *not* mark this string for translation. %s is a copyright symbol suitable for this locale, and %d is the copyright year. */ "Copyright 2011-%s %d Simon Josefsson, Tim Ruehsen."; static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --no-alabelroundtrip Disable ALabel rountrip for lookups\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); } static void hexdump (const char *prefix, const char *str) { uint8_t *u8; uint32_t *u32 = NULL; size_t u32len; size_t i; const char *encoding = locale_charset (); u8 = u8_strconv_from_encoding (str, encoding, iconveh_error); if (u8) u32 = u8_to_u32 (u8, strlen ((char *) u8), NULL, &u32len); for (i = 0; i < strlen (str); i++) fprintf (stderr, "%s[%lu] = 0x%02x\n", prefix, (unsigned long) i, (unsigned) (str[i] & 0xFF)); if (u8 && strcmp (str, (char *) u8) != 0) for (i = 0; i < strlen ((char *) u8); i++) fprintf (stderr, "UTF-8 %s[%lu] = 0x%02x\n", prefix, (unsigned long) i, u8[i] & 0xFF); if (u8 && u32) for (i = 0; i < u32len; i++) fprintf (stderr, "UCS-4 %s[%lu] = U+%04x\n", prefix, (unsigned long) i, u32[i]); } static struct gengetopt_args_info args_info; static void process_input (char *readbuf, int flags) { size_t len = strlen (readbuf); char *output; const char *tag; int rc; if (len && readbuf[len - 1] == '\n') readbuf[len - 1] = '\0'; if (strcmp (readbuf, "show w") == 0) { puts (WARRANTY); return; } else if (strcmp (readbuf, "show c") == 0) { puts (CONDITIONS); return; } if (args_info.debug_given) hexdump ("input", readbuf); if (args_info.register_given) { rc = idn2_register_ul(readbuf, NULL, &output, flags); tag = "register"; } else if (args_info.decode_given) { rc = idn2_to_unicode_lzlz (readbuf, &output, 0); tag = "decode"; } else { rc = idn2_to_ascii_lz (readbuf, &output, flags); tag = "toAscii"; } if (rc == IDN2_OK) { if (args_info.debug_given) hexdump ("output", readbuf); printf ("%s\n", output); free (output); } else error (EXIT_FAILURE, 0, "%s: %s", tag, idn2_strerror (rc)); } int main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson, Tim Ruehsen", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; if (flags && args_info.no_alabelroundtrip_given) flags |= IDN2_NO_ALABEL_ROUNDTRIP; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson, Tim Ruehsen", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; if (flags && args_info.no_alabelroundtrip_given) flags |= IDN2_NO_ALABEL_ROUNDTRIP; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
{'added': [(2, ' Copyright (C) 2011-2019 Simon Josefsson, Tim Ruehsen'), (53, ' "Copyright 2011-%s %d Simon Josefsson, Tim Ruehsen.";'), (81, ' -h, --help Print help and exit\\n\\'), (82, ' -V, --version Print version and exit\\n\\'), (85, ' -d, --decode Decode (punycode) domain name\\n\\'), (86, ' -l, --lookup Lookup domain name (default)\\n\\'), (87, ' -r, --register Register label\\n\\'), (90, ' -T, --tr46t Enable TR46 transitional processing\\n\\'), (91, ' -N, --tr46nt Enable TR46 non-transitional processing\\n\\'), (92, ' --no-tr46 Disable TR46 processing\\n\\'), (95, ' --usestd3asciirules Enable STD3 ASCII rules\\n\\'), (96, ' --no-alabelroundtrip Disable ALabel rountrip for lookups\\n\\'), (97, ' --debug Print debugging information\\n\\'), (98, ' --quiet Silent operation\\n\\'), (205, '\t\t "Simon Josefsson, Tim Ruehsen", (char *) NULL);'), (234, ' if (flags && args_info.no_alabelroundtrip_given)'), (235, ' flags |= IDN2_NO_ALABEL_ROUNDTRIP;'), (236, '')], 'deleted': [(2, ' Copyright (C) 2011-2017 Simon Josefsson'), (53, ' "Copyright %s %d Simon Josefsson.";'), (81, ' -h, --help Print help and exit\\n\\'), (82, ' -V, --version Print version and exit\\n\\'), (85, ' -d, --decode Decode (punycode) domain name\\n\\'), (86, ' -l, --lookup Lookup domain name (default)\\n\\'), (87, ' -r, --register Register label\\n\\'), (90, ' -T, --tr46t Enable TR46 transitional processing\\n\\'), (91, ' -N, --tr46nt Enable TR46 non-transitional processing\\n\\'), (92, ' --no-tr46 Disable TR46 processing\\n\\'), (95, ' --usestd3asciirules Enable STD3 ASCII rules\\n\\'), (96, ' --debug Print debugging information\\n\\'), (97, ' --quiet Silent operation\\n\\'), (204, '\t\t "Simon Josefsson", (char *) NULL);')]}
18
14
194
962
https://gitlab.com/libidn/libidn2
CVE-2019-12290
['CWE-20']
idn2.c
usage
/* idn2.c - command line interface to libidn2 Copyright (C) 2011-2017 Simon Josefsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <locale.h> #include <unistd.h> #include <idn2.h> #include <unitypes.h> #include <uniconv.h> #include <unistr.h> #include <unistring/localcharset.h> /* Gnulib headers. */ #include "error.h" #include "gettext.h" #define _(String) dgettext (PACKAGE, String) #include "progname.h" #include "version-etc.h" #include "idn2_cmd.h" #include "blurbs.h" #ifdef __cplusplus extern // define a global const variable in C++, C doesn't need it. #endif const char version_etc_copyright[] = /* Do *not* mark this string for translation. %s is a copyright symbol suitable for this locale, and %d is the copyright year. */ "Copyright %s %d Simon Josefsson."; static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); } static void hexdump (const char *prefix, const char *str) { uint8_t *u8; uint32_t *u32 = NULL; size_t u32len; size_t i; const char *encoding = locale_charset (); u8 = u8_strconv_from_encoding (str, encoding, iconveh_error); if (u8) u32 = u8_to_u32 (u8, strlen ((char *) u8), NULL, &u32len); for (i = 0; i < strlen (str); i++) fprintf (stderr, "%s[%lu] = 0x%02x\n", prefix, (unsigned long) i, (unsigned) (str[i] & 0xFF)); if (u8 && strcmp (str, (char *) u8) != 0) for (i = 0; i < strlen ((char *) u8); i++) fprintf (stderr, "UTF-8 %s[%lu] = 0x%02x\n", prefix, (unsigned long) i, u8[i] & 0xFF); if (u8 && u32) for (i = 0; i < u32len; i++) fprintf (stderr, "UCS-4 %s[%lu] = U+%04x\n", prefix, (unsigned long) i, u32[i]); } static struct gengetopt_args_info args_info; static void process_input (char *readbuf, int flags) { size_t len = strlen (readbuf); char *output; const char *tag; int rc; if (len && readbuf[len - 1] == '\n') readbuf[len - 1] = '\0'; if (strcmp (readbuf, "show w") == 0) { puts (WARRANTY); return; } else if (strcmp (readbuf, "show c") == 0) { puts (CONDITIONS); return; } if (args_info.debug_given) hexdump ("input", readbuf); if (args_info.register_given) { rc = idn2_register_ul(readbuf, NULL, &output, flags); tag = "register"; } else if (args_info.decode_given) { rc = idn2_to_unicode_lzlz (readbuf, &output, 0); tag = "decode"; } else { rc = idn2_to_ascii_lz (readbuf, &output, flags); tag = "toAscii"; } if (rc == IDN2_OK) { if (args_info.debug_given) hexdump ("output", readbuf); printf ("%s\n", output); free (output); } else error (EXIT_FAILURE, 0, "%s: %s", tag, idn2_strerror (rc)); } int main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
/* idn2.c - command line interface to libidn2 Copyright (C) 2011-2019 Simon Josefsson, Tim Ruehsen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <locale.h> #include <unistd.h> #include <idn2.h> #include <unitypes.h> #include <uniconv.h> #include <unistr.h> #include <unistring/localcharset.h> /* Gnulib headers. */ #include "error.h" #include "gettext.h" #define _(String) dgettext (PACKAGE, String) #include "progname.h" #include "version-etc.h" #include "idn2_cmd.h" #include "blurbs.h" #ifdef __cplusplus extern // define a global const variable in C++, C doesn't need it. #endif const char version_etc_copyright[] = /* Do *not* mark this string for translation. %s is a copyright symbol suitable for this locale, and %d is the copyright year. */ "Copyright 2011-%s %d Simon Josefsson, Tim Ruehsen."; static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --no-alabelroundtrip Disable ALabel rountrip for lookups\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); } static void hexdump (const char *prefix, const char *str) { uint8_t *u8; uint32_t *u32 = NULL; size_t u32len; size_t i; const char *encoding = locale_charset (); u8 = u8_strconv_from_encoding (str, encoding, iconveh_error); if (u8) u32 = u8_to_u32 (u8, strlen ((char *) u8), NULL, &u32len); for (i = 0; i < strlen (str); i++) fprintf (stderr, "%s[%lu] = 0x%02x\n", prefix, (unsigned long) i, (unsigned) (str[i] & 0xFF)); if (u8 && strcmp (str, (char *) u8) != 0) for (i = 0; i < strlen ((char *) u8); i++) fprintf (stderr, "UTF-8 %s[%lu] = 0x%02x\n", prefix, (unsigned long) i, u8[i] & 0xFF); if (u8 && u32) for (i = 0; i < u32len; i++) fprintf (stderr, "UCS-4 %s[%lu] = U+%04x\n", prefix, (unsigned long) i, u32[i]); } static struct gengetopt_args_info args_info; static void process_input (char *readbuf, int flags) { size_t len = strlen (readbuf); char *output; const char *tag; int rc; if (len && readbuf[len - 1] == '\n') readbuf[len - 1] = '\0'; if (strcmp (readbuf, "show w") == 0) { puts (WARRANTY); return; } else if (strcmp (readbuf, "show c") == 0) { puts (CONDITIONS); return; } if (args_info.debug_given) hexdump ("input", readbuf); if (args_info.register_given) { rc = idn2_register_ul(readbuf, NULL, &output, flags); tag = "register"; } else if (args_info.decode_given) { rc = idn2_to_unicode_lzlz (readbuf, &output, 0); tag = "decode"; } else { rc = idn2_to_ascii_lz (readbuf, &output, flags); tag = "toAscii"; } if (rc == IDN2_OK) { if (args_info.debug_given) hexdump ("output", readbuf); printf ("%s\n", output); free (output); } else error (EXIT_FAILURE, 0, "%s: %s", tag, idn2_strerror (rc)); } int main (int argc, char *argv[]) { unsigned cmdn; int flags = IDN2_NONTRANSITIONAL; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn2", PACKAGE_NAME, VERSION, "Simon Josefsson, Tim Ruehsen", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset: %s\n"), locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s", _("Type each input string on a line by itself, " "terminated by a newline character.\n")); if (args_info.tr46t_given) flags = IDN2_TRANSITIONAL; else if (args_info.tr46nt_given) flags = IDN2_NONTRANSITIONAL; else if (args_info.no_tr46_given) flags = IDN2_NO_TR46; if (flags && args_info.usestd3asciirules_given) flags |= IDN2_USE_STD3_ASCII_RULES; if (flags && args_info.no_alabelroundtrip_given) flags |= IDN2_NO_ALABEL_ROUNDTRIP; for (cmdn = 0; cmdn < args_info.inputs_num; cmdn++) process_input (args_info.inputs[cmdn], flags | IDN2_NFC_INPUT); if (!cmdn) { char *buf = NULL; size_t bufsize = 0; while (getline (&buf, &bufsize, stdin) > 0) process_input (buf, flags); free (buf); } if (ferror (stdin)) error (EXIT_FAILURE, errno, "%s", _("input error")); cmdline_parser_free (&args_info); return EXIT_SUCCESS; }
usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); }
usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION]... [STRINGS]...\n\ "), program_name); fputs (_("\ Internationalized Domain Name (IDNA2008) convert STRINGS, or standard input.\n\ \n\ "), stdout); fputs (_("\ Command line interface to the Libidn2 implementation of IDNA2008.\n\ \n\ All strings are expected to be encoded in the locale charset.\n\ \n\ To process a string that starts with `-', for example `-foo', use `--'\n\ to signal the end of parameters, as in `idn2 --quiet -- -foo'.\n\ \n\ Mandatory arguments to long options are mandatory for short options too.\n\ "), stdout); fputs (_("\ -h, --help Print help and exit\n\ -V, --version Print version and exit\n\ "), stdout); fputs (_("\ -d, --decode Decode (punycode) domain name\n\ -l, --lookup Lookup domain name (default)\n\ -r, --register Register label\n\ "), stdout); fputs (_("\ -T, --tr46t Enable TR46 transitional processing\n\ -N, --tr46nt Enable TR46 non-transitional processing\n\ --no-tr46 Disable TR46 processing\n\ "), stdout); fputs (_("\ --usestd3asciirules Enable STD3 ASCII rules\n\ --no-alabelroundtrip Disable ALabel rountrip for lookups\n\ --debug Print debugging information\n\ --quiet Silent operation\n\ "), stdout); emit_bug_reporting_address (); } exit (status); }
{'added': [(2, ' Copyright (C) 2011-2019 Simon Josefsson, Tim Ruehsen'), (53, ' "Copyright 2011-%s %d Simon Josefsson, Tim Ruehsen.";'), (81, ' -h, --help Print help and exit\\n\\'), (82, ' -V, --version Print version and exit\\n\\'), (85, ' -d, --decode Decode (punycode) domain name\\n\\'), (86, ' -l, --lookup Lookup domain name (default)\\n\\'), (87, ' -r, --register Register label\\n\\'), (90, ' -T, --tr46t Enable TR46 transitional processing\\n\\'), (91, ' -N, --tr46nt Enable TR46 non-transitional processing\\n\\'), (92, ' --no-tr46 Disable TR46 processing\\n\\'), (95, ' --usestd3asciirules Enable STD3 ASCII rules\\n\\'), (96, ' --no-alabelroundtrip Disable ALabel rountrip for lookups\\n\\'), (97, ' --debug Print debugging information\\n\\'), (98, ' --quiet Silent operation\\n\\'), (205, '\t\t "Simon Josefsson, Tim Ruehsen", (char *) NULL);'), (234, ' if (flags && args_info.no_alabelroundtrip_given)'), (235, ' flags |= IDN2_NO_ALABEL_ROUNDTRIP;'), (236, '')], 'deleted': [(2, ' Copyright (C) 2011-2017 Simon Josefsson'), (53, ' "Copyright %s %d Simon Josefsson.";'), (81, ' -h, --help Print help and exit\\n\\'), (82, ' -V, --version Print version and exit\\n\\'), (85, ' -d, --decode Decode (punycode) domain name\\n\\'), (86, ' -l, --lookup Lookup domain name (default)\\n\\'), (87, ' -r, --register Register label\\n\\'), (90, ' -T, --tr46t Enable TR46 transitional processing\\n\\'), (91, ' -N, --tr46nt Enable TR46 non-transitional processing\\n\\'), (92, ' --no-tr46 Disable TR46 processing\\n\\'), (95, ' --usestd3asciirules Enable STD3 ASCII rules\\n\\'), (96, ' --debug Print debugging information\\n\\'), (97, ' --quiet Silent operation\\n\\'), (204, '\t\t "Simon Josefsson", (char *) NULL);')]}
18
14
194
962
https://gitlab.com/libidn/libidn2
CVE-2019-12290
['CWE-20']
parser.c
PyParser_AddToken
/* Parser implementation */ /* For a description, see the comments at end of this file */ /* XXX To do: error recovery */ #include "Python.h" #include "pgenheaders.h" #include "token.h" #include "grammar.h" #include "node.h" #include "parser.h" #include "errcode.h" #ifdef Py_DEBUG extern int Py_DebugFlag; #define D(x) if (!Py_DebugFlag); else x #else #define D(x) #endif /* STACK DATA TYPE */ static void s_reset(stack *); static void s_reset(stack *s) { s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) static int s_push(stack *s, dfa *d, node *parent) { stackentry *top; if (s->s_top == s->s_base) { fprintf(stderr, "s_push: parser stack overflow\n"); return E_NOMEM; } top = --s->s_top; top->s_dfa = d; top->s_parent = parent; top->s_state = 0; return 0; } #ifdef Py_DEBUG static void s_pop(stack *s) { if (s_empty(s)) Py_FatalError("s_pop: parser stack underflow -- FATAL"); s->s_top++; } #else /* !Py_DEBUG */ #define s_pop(s) (s)->s_top++ #endif /* PARSER CREATION */ parser_state * PyParser_New(grammar *g, int start) { parser_state *ps; if (!g->g_accel) PyGrammar_AddAccelerators(g); ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); if (ps == NULL) return NULL; ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD ps->p_flags = 0; #endif ps->p_tree = PyNode_New(start); if (ps->p_tree == NULL) { PyMem_FREE(ps); return NULL; } s_reset(&ps->p_stack); (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); return ps; } void PyParser_Delete(parser_state *ps) { /* NB If you want to save the parse tree, you must set p_tree to NULL before calling delparser! */ PyNode_Free(ps->p_tree); PyMem_FREE(ps); } /* PARSER STACK OPERATIONS */ static int shift(stack *s, int type, char *str, int newstate, int lineno, int col_offset, int end_lineno, int end_col_offset) { int err; assert(!s_empty(s)); err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset, end_lineno, end_col_offset); if (err) return err; s->s_top->s_state = newstate; return 0; } static int push(stack *s, int type, dfa *d, int newstate, int lineno, int col_offset, int end_lineno, int end_col_offset) { int err; node *n; n = s->s_top->s_parent; assert(!s_empty(s)); err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset, end_lineno, end_col_offset); if (err) return err; s->s_top->s_state = newstate; return s_push(s, d, CHILD(n, NCH(n)-1)); } /* PARSER PROPER */ static int classify(parser_state *ps, int type, const char *str) { grammar *g = ps->p_grammar; int n = g->g_ll.ll_nlabels; if (type == NAME) { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type != NAME || l->lb_str == NULL || l->lb_str[0] != str[0] || strcmp(l->lb_str, str) != 0) continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { if (str[0] == 'w' && strcmp(str, "with") == 0) break; /* not a keyword yet */ else if (str[0] == 'a' && strcmp(str, "as") == 0) break; /* not a keyword yet */ } #endif #endif D(printf("It's a keyword\n")); return n - i; } } { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type == type && l->lb_str == NULL) { D(printf("It's a token we know\n")); return n - i; } } } D(printf("Illegal token\n")); return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ static void future_hack(parser_state *ps) { node *n = ps->p_stack.s_top->s_parent; node *ch, *cch; int i; /* from __future__ import ..., must have at least 4 children */ n = CHILD(n, 0); if (NCH(n) < 4) return; ch = CHILD(n, 0); if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) return; ch = CHILD(n, 1); if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && strcmp(STR(CHILD(ch, 0)), "__future__") != 0) return; ch = CHILD(n, 3); /* ch can be a star, a parenthesis or import_as_names */ if (TYPE(ch) == STAR) return; if (TYPE(ch) == LPAR) ch = CHILD(n, 4); for (i = 0; i < NCH(ch); i += 2) { cch = CHILD(ch, i); if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { char *str_ch = STR(CHILD(cch, 0)); if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { ps->p_flags |= CO_FUTURE_WITH_STATEMENT; } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; } } } } #endif #endif /* future keyword */ int PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push ...\n")); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } } #ifdef Py_DEBUG /* DEBUG OUTPUT */ void dumptree(grammar *g, node *n) { int i; if (n == NULL) printf("NIL"); else { label l; l.lb_type = TYPE(n); l.lb_str = STR(n); printf("%s", PyGrammar_LabelRepr(&l)); if (ISNONTERMINAL(TYPE(n))) { printf("("); for (i = 0; i < NCH(n); i++) { if (i > 0) printf(","); dumptree(g, CHILD(n, i)); } printf(")"); } } } void showtree(grammar *g, node *n) { int i; if (n == NULL) return; if (ISNONTERMINAL(TYPE(n))) { for (i = 0; i < NCH(n); i++) showtree(g, CHILD(n, i)); } else if (ISTERMINAL(TYPE(n))) { printf("%s", _PyParser_TokenNames[TYPE(n)]); if (TYPE(n) == NUMBER || TYPE(n) == NAME) printf("(%s)", STR(n)); printf(" "); } else printf("? "); } void printtree(parser_state *ps) { if (Py_DebugFlag) { printf("Parse tree:\n"); dumptree(ps->p_grammar, ps->p_tree); printf("\n"); printf("Tokens:\n"); showtree(ps->p_grammar, ps->p_tree); printf("\n"); } printf("Listing:\n"); PyNode_ListTree(ps->p_tree); printf("\n"); } #endif /* Py_DEBUG */ /* Description ----------- The parser's interface is different than usual: the function addtoken() must be called for each token in the input. This makes it possible to turn it into an incremental parsing system later. The parsing system constructs a parse tree as it goes. A parsing rule is represented as a Deterministic Finite-state Automaton (DFA). A node in a DFA represents a state of the parser; an arc represents a transition. Transitions are either labeled with terminal symbols or with non-terminals. When the parser decides to follow an arc labeled with a non-terminal, it is invoked recursively with the DFA representing the parsing rule for that as its initial state; when that DFA accepts, the parser that invoked it continues. The parse tree constructed by the recursively called parser is inserted as a child in the current parse tree. The DFA's can be constructed automatically from a more conventional language description. An extended LL(1) grammar (ELL(1)) is suitable. Certain restrictions make the parser's life easier: rules that can produce the empty string should be outlawed (there are other ways to put loops or optional parts in the language). To avoid the need to construct FIRST sets, we can require that all but the last alternative of a rule (really: arc going out of a DFA's state) must begin with a terminal symbol. As an example, consider this grammar: expr: term (OP term)* term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> ^ | | | \----OP----/ The parse tree generated for the input a+b is: (expr: (term: (NAME: a)), (OP: +), (term: (NAME: b))) */
/* Parser implementation */ /* For a description, see the comments at end of this file */ /* XXX To do: error recovery */ #include "Python.h" #include "pgenheaders.h" #include "token.h" #include "grammar.h" #include "node.h" #include "parser.h" #include "errcode.h" #include "graminit.h" #ifdef Py_DEBUG extern int Py_DebugFlag; #define D(x) if (!Py_DebugFlag); else x #else #define D(x) #endif /* STACK DATA TYPE */ static void s_reset(stack *); static void s_reset(stack *s) { s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) static int s_push(stack *s, dfa *d, node *parent) { stackentry *top; if (s->s_top == s->s_base) { fprintf(stderr, "s_push: parser stack overflow\n"); return E_NOMEM; } top = --s->s_top; top->s_dfa = d; top->s_parent = parent; top->s_state = 0; return 0; } #ifdef Py_DEBUG static void s_pop(stack *s) { if (s_empty(s)) Py_FatalError("s_pop: parser stack underflow -- FATAL"); s->s_top++; } #else /* !Py_DEBUG */ #define s_pop(s) (s)->s_top++ #endif /* PARSER CREATION */ parser_state * PyParser_New(grammar *g, int start) { parser_state *ps; if (!g->g_accel) PyGrammar_AddAccelerators(g); ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); if (ps == NULL) return NULL; ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD ps->p_flags = 0; #endif ps->p_tree = PyNode_New(start); if (ps->p_tree == NULL) { PyMem_FREE(ps); return NULL; } s_reset(&ps->p_stack); (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); return ps; } void PyParser_Delete(parser_state *ps) { /* NB If you want to save the parse tree, you must set p_tree to NULL before calling delparser! */ PyNode_Free(ps->p_tree); PyMem_FREE(ps); } /* PARSER STACK OPERATIONS */ static int shift(stack *s, int type, char *str, int newstate, int lineno, int col_offset, int end_lineno, int end_col_offset) { int err; assert(!s_empty(s)); err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset, end_lineno, end_col_offset); if (err) return err; s->s_top->s_state = newstate; return 0; } static int push(stack *s, int type, dfa *d, int newstate, int lineno, int col_offset, int end_lineno, int end_col_offset) { int err; node *n; n = s->s_top->s_parent; assert(!s_empty(s)); err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset, end_lineno, end_col_offset); if (err) return err; s->s_top->s_state = newstate; return s_push(s, d, CHILD(n, NCH(n)-1)); } /* PARSER PROPER */ static int classify(parser_state *ps, int type, const char *str) { grammar *g = ps->p_grammar; int n = g->g_ll.ll_nlabels; if (type == NAME) { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type != NAME || l->lb_str == NULL || l->lb_str[0] != str[0] || strcmp(l->lb_str, str) != 0) continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { if (str[0] == 'w' && strcmp(str, "with") == 0) break; /* not a keyword yet */ else if (str[0] == 'a' && strcmp(str, "as") == 0) break; /* not a keyword yet */ } #endif #endif D(printf("It's a keyword\n")); return n - i; } } { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type == type && l->lb_str == NULL) { D(printf("It's a token we know\n")); return n - i; } } } D(printf("Illegal token\n")); return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ static void future_hack(parser_state *ps) { node *n = ps->p_stack.s_top->s_parent; node *ch, *cch; int i; /* from __future__ import ..., must have at least 4 children */ n = CHILD(n, 0); if (NCH(n) < 4) return; ch = CHILD(n, 0); if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) return; ch = CHILD(n, 1); if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && strcmp(STR(CHILD(ch, 0)), "__future__") != 0) return; ch = CHILD(n, 3); /* ch can be a star, a parenthesis or import_as_names */ if (TYPE(ch) == STAR) return; if (TYPE(ch) == LPAR) ch = CHILD(n, 4); for (i = 0; i < NCH(ch); i += 2) { cch = CHILD(ch, i); if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { char *str_ch = STR(CHILD(cch, 0)); if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { ps->p_flags |= CO_FUTURE_WITH_STATEMENT; } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; } } } } #endif #endif /* future keyword */ int PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1; if (nt == func_body_suite && !(ps->p_flags & PyCF_TYPE_COMMENTS)) { /* When parsing type comments is not requested, we can provide better errors about bad indentation by using 'suite' for the body of a funcdef */ D(printf(" [switch func_body_suite to suite]")); nt = suite; } d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push '%s'\n", d1->d_name)); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } } #ifdef Py_DEBUG /* DEBUG OUTPUT */ void dumptree(grammar *g, node *n) { int i; if (n == NULL) printf("NIL"); else { label l; l.lb_type = TYPE(n); l.lb_str = STR(n); printf("%s", PyGrammar_LabelRepr(&l)); if (ISNONTERMINAL(TYPE(n))) { printf("("); for (i = 0; i < NCH(n); i++) { if (i > 0) printf(","); dumptree(g, CHILD(n, i)); } printf(")"); } } } void showtree(grammar *g, node *n) { int i; if (n == NULL) return; if (ISNONTERMINAL(TYPE(n))) { for (i = 0; i < NCH(n); i++) showtree(g, CHILD(n, i)); } else if (ISTERMINAL(TYPE(n))) { printf("%s", _PyParser_TokenNames[TYPE(n)]); if (TYPE(n) == NUMBER || TYPE(n) == NAME) printf("(%s)", STR(n)); printf(" "); } else printf("? "); } void printtree(parser_state *ps) { if (Py_DebugFlag) { printf("Parse tree:\n"); dumptree(ps->p_grammar, ps->p_tree); printf("\n"); printf("Tokens:\n"); showtree(ps->p_grammar, ps->p_tree); printf("\n"); } printf("Listing:\n"); PyNode_ListTree(ps->p_tree); printf("\n"); } #endif /* Py_DEBUG */ /* Description ----------- The parser's interface is different than usual: the function addtoken() must be called for each token in the input. This makes it possible to turn it into an incremental parsing system later. The parsing system constructs a parse tree as it goes. A parsing rule is represented as a Deterministic Finite-state Automaton (DFA). A node in a DFA represents a state of the parser; an arc represents a transition. Transitions are either labeled with terminal symbols or with non-terminals. When the parser decides to follow an arc labeled with a non-terminal, it is invoked recursively with the DFA representing the parsing rule for that as its initial state; when that DFA accepts, the parser that invoked it continues. The parse tree constructed by the recursively called parser is inserted as a child in the current parse tree. The DFA's can be constructed automatically from a more conventional language description. An extended LL(1) grammar (ELL(1)) is suitable. Certain restrictions make the parser's life easier: rules that can produce the empty string should be outlawed (there are other ways to put loops or optional parts in the language). To avoid the need to construct FIRST sets, we can require that all but the last alternative of a rule (really: arc going out of a DFA's state) must begin with a terminal symbol. As an example, consider this grammar: expr: term (OP term)* term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> ^ | | | \----OP----/ The parse tree generated for the input a+b is: (expr: (term: (NAME: a)), (OP: +), (term: (NAME: b))) */
PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push ...\n")); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } }
PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1; if (nt == func_body_suite && !(ps->p_flags & PyCF_TYPE_COMMENTS)) { /* When parsing type comments is not requested, we can provide better errors about bad indentation by using 'suite' for the body of a funcdef */ D(printf(" [switch func_body_suite to suite]")); nt = suite; } d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push '%s'\n", d1->d_name)); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } }
{'added': [(15, '#include "graminit.h"'), (264, ' dfa *d1;'), (265, ' if (nt == func_body_suite && !(ps->p_flags & PyCF_TYPE_COMMENTS)) {'), (266, ' /* When parsing type comments is not requested,'), (267, ' we can provide better errors about bad indentation'), (268, " by using 'suite' for the body of a funcdef */"), (269, ' D(printf(" [switch func_body_suite to suite]"));'), (270, ' nt = suite;'), (271, ' }'), (272, ' d1 = PyGrammar_FindDFA('), (280, ' D(printf(" Push \'%s\'\\n", d1->d_name));')], 'deleted': [(263, ' dfa *d1 = PyGrammar_FindDFA('), (271, ' D(printf(" Push ...\\n"));')]}
11
2
308
1,982
https://github.com/python/cpython
CVE-2019-19274
['CWE-125']
f2fs.h
F2FS_P_SB
// SPDX-License-Identifier: GPL-2.0 /* * fs/f2fs/f2fs.h * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ */ #ifndef _LINUX_F2FS_H #define _LINUX_F2FS_H #include <linux/uio.h> #include <linux/types.h> #include <linux/page-flags.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/crc32.h> #include <linux/magic.h> #include <linux/kobject.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/vmalloc.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/quotaops.h> #include <crypto/hash.h> #include <linux/fscrypt.h> #ifdef CONFIG_F2FS_CHECK_FS #define f2fs_bug_on(sbi, condition) BUG_ON(condition) #else #define f2fs_bug_on(sbi, condition) \ do { \ if (unlikely(condition)) { \ WARN_ON(1); \ set_sbi_flag(sbi, SBI_NEED_FSCK); \ } \ } while (0) #endif enum { FAULT_KMALLOC, FAULT_KVMALLOC, FAULT_PAGE_ALLOC, FAULT_PAGE_GET, FAULT_ALLOC_BIO, FAULT_ALLOC_NID, FAULT_ORPHAN, FAULT_BLOCK, FAULT_DIR_DEPTH, FAULT_EVICT_INODE, FAULT_TRUNCATE, FAULT_READ_IO, FAULT_CHECKPOINT, FAULT_DISCARD, FAULT_WRITE_IO, FAULT_MAX, }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define F2FS_ALL_FAULT_TYPE ((1 << FAULT_MAX) - 1) struct f2fs_fault_info { atomic_t inject_ops; unsigned int inject_rate; unsigned int inject_type; }; extern const char *f2fs_fault_name[FAULT_MAX]; #define IS_FAULT_SET(fi, type) ((fi)->inject_type & (1 << (type))) #endif /* * For mount options */ #define F2FS_MOUNT_BG_GC 0x00000001 #define F2FS_MOUNT_DISABLE_ROLL_FORWARD 0x00000002 #define F2FS_MOUNT_DISCARD 0x00000004 #define F2FS_MOUNT_NOHEAP 0x00000008 #define F2FS_MOUNT_XATTR_USER 0x00000010 #define F2FS_MOUNT_POSIX_ACL 0x00000020 #define F2FS_MOUNT_DISABLE_EXT_IDENTIFY 0x00000040 #define F2FS_MOUNT_INLINE_XATTR 0x00000080 #define F2FS_MOUNT_INLINE_DATA 0x00000100 #define F2FS_MOUNT_INLINE_DENTRY 0x00000200 #define F2FS_MOUNT_FLUSH_MERGE 0x00000400 #define F2FS_MOUNT_NOBARRIER 0x00000800 #define F2FS_MOUNT_FASTBOOT 0x00001000 #define F2FS_MOUNT_EXTENT_CACHE 0x00002000 #define F2FS_MOUNT_FORCE_FG_GC 0x00004000 #define F2FS_MOUNT_DATA_FLUSH 0x00008000 #define F2FS_MOUNT_FAULT_INJECTION 0x00010000 #define F2FS_MOUNT_ADAPTIVE 0x00020000 #define F2FS_MOUNT_LFS 0x00040000 #define F2FS_MOUNT_USRQUOTA 0x00080000 #define F2FS_MOUNT_GRPQUOTA 0x00100000 #define F2FS_MOUNT_PRJQUOTA 0x00200000 #define F2FS_MOUNT_QUOTA 0x00400000 #define F2FS_MOUNT_INLINE_XATTR_SIZE 0x00800000 #define F2FS_MOUNT_RESERVE_ROOT 0x01000000 #define F2FS_MOUNT_DISABLE_CHECKPOINT 0x02000000 #define F2FS_OPTION(sbi) ((sbi)->mount_opt) #define clear_opt(sbi, option) (F2FS_OPTION(sbi).opt &= ~F2FS_MOUNT_##option) #define set_opt(sbi, option) (F2FS_OPTION(sbi).opt |= F2FS_MOUNT_##option) #define test_opt(sbi, option) (F2FS_OPTION(sbi).opt & F2FS_MOUNT_##option) #define ver_after(a, b) (typecheck(unsigned long long, a) && \ typecheck(unsigned long long, b) && \ ((long long)((a) - (b)) > 0)) typedef u32 block_t; /* * should not change u32, since it is the on-disk block * address format, __le32. */ typedef u32 nid_t; struct f2fs_mount_info { unsigned int opt; int write_io_size_bits; /* Write IO size bits */ block_t root_reserved_blocks; /* root reserved blocks */ kuid_t s_resuid; /* reserved blocks for uid */ kgid_t s_resgid; /* reserved blocks for gid */ int active_logs; /* # of active logs */ int inline_xattr_size; /* inline xattr size */ #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info fault_info; /* For fault injection */ #endif #ifdef CONFIG_QUOTA /* Names of quota files with journalled quota */ char *s_qf_names[MAXQUOTAS]; int s_jquota_fmt; /* Format of quota to use */ #endif /* For which write hints are passed down to block layer */ int whint_mode; int alloc_mode; /* segment allocation policy */ int fsync_mode; /* fsync policy */ bool test_dummy_encryption; /* test dummy encryption */ block_t unusable_cap; /* Amount of space allowed to be * unusable when disabling checkpoint */ }; #define F2FS_FEATURE_ENCRYPT 0x0001 #define F2FS_FEATURE_BLKZONED 0x0002 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004 #define F2FS_FEATURE_EXTRA_ATTR 0x0008 #define F2FS_FEATURE_PRJQUOTA 0x0010 #define F2FS_FEATURE_INODE_CHKSUM 0x0020 #define F2FS_FEATURE_FLEXIBLE_INLINE_XATTR 0x0040 #define F2FS_FEATURE_QUOTA_INO 0x0080 #define F2FS_FEATURE_INODE_CRTIME 0x0100 #define F2FS_FEATURE_LOST_FOUND 0x0200 #define F2FS_FEATURE_VERITY 0x0400 /* reserved */ #define F2FS_FEATURE_SB_CHKSUM 0x0800 #define __F2FS_HAS_FEATURE(raw_super, mask) \ ((raw_super->feature & cpu_to_le32(mask)) != 0) #define F2FS_HAS_FEATURE(sbi, mask) __F2FS_HAS_FEATURE(sbi->raw_super, mask) #define F2FS_SET_FEATURE(sbi, mask) \ (sbi->raw_super->feature |= cpu_to_le32(mask)) #define F2FS_CLEAR_FEATURE(sbi, mask) \ (sbi->raw_super->feature &= ~cpu_to_le32(mask)) /* * Default values for user and/or group using reserved blocks */ #define F2FS_DEF_RESUID 0 #define F2FS_DEF_RESGID 0 /* * For checkpoint manager */ enum { NAT_BITMAP, SIT_BITMAP }; #define CP_UMOUNT 0x00000001 #define CP_FASTBOOT 0x00000002 #define CP_SYNC 0x00000004 #define CP_RECOVERY 0x00000008 #define CP_DISCARD 0x00000010 #define CP_TRIMMED 0x00000020 #define CP_PAUSE 0x00000040 #define MAX_DISCARD_BLOCKS(sbi) BLKS_PER_SEC(sbi) #define DEF_MAX_DISCARD_REQUEST 8 /* issue 8 discards per round */ #define DEF_MIN_DISCARD_ISSUE_TIME 50 /* 50 ms, if exists */ #define DEF_MID_DISCARD_ISSUE_TIME 500 /* 500 ms, if device busy */ #define DEF_MAX_DISCARD_ISSUE_TIME 60000 /* 60 s, if no candidates */ #define DEF_DISCARD_URGENT_UTIL 80 /* do more discard over 80% */ #define DEF_CP_INTERVAL 60 /* 60 secs */ #define DEF_IDLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_QUICK_INTERVAL 1 /* 1 secs */ #define DEF_UMOUNT_DISCARD_TIMEOUT 5 /* 5 secs */ struct cp_control { int reason; __u64 trim_start; __u64 trim_end; __u64 trim_minlen; }; /* * indicate meta/data type */ enum { META_CP, META_NAT, META_SIT, META_SSA, META_MAX, META_POR, DATA_GENERIC, /* check range only */ DATA_GENERIC_ENHANCE, /* strong check on range and segment bitmap */ DATA_GENERIC_ENHANCE_READ, /* * strong check on range and segment * bitmap but no warning due to race * condition of read on truncated area * by extent_cache */ META_GENERIC, }; /* for the list of ino */ enum { ORPHAN_INO, /* for orphan ino list */ APPEND_INO, /* for append ino list */ UPDATE_INO, /* for update ino list */ TRANS_DIR_INO, /* for trasactions dir ino list */ FLUSH_INO, /* for multiple device flushing */ MAX_INO_ENTRY, /* max. list */ }; struct ino_entry { struct list_head list; /* list head */ nid_t ino; /* inode number */ unsigned int dirty_device; /* dirty device bitmap */ }; /* for the list of inodes to be GCed */ struct inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ }; struct fsync_node_entry { struct list_head list; /* list head */ struct page *page; /* warm node page pointer */ unsigned int seq_id; /* sequence id */ }; /* for the bitmap indicate blocks to be discarded */ struct discard_entry { struct list_head list; /* list head */ block_t start_blkaddr; /* start blockaddr of current segment */ unsigned char discard_map[SIT_VBLOCK_MAP_SIZE]; /* segment discard bitmap */ }; /* default discard granularity of inner discard thread, unit: block count */ #define DEFAULT_DISCARD_GRANULARITY 16 /* max discard pend list number */ #define MAX_PLIST_NUM 512 #define plist_idx(blk_num) ((blk_num) >= MAX_PLIST_NUM ? \ (MAX_PLIST_NUM - 1) : ((blk_num) - 1)) enum { D_PREP, /* initial */ D_PARTIAL, /* partially submitted */ D_SUBMIT, /* all submitted */ D_DONE, /* finished */ }; struct discard_info { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_cmd { struct rb_node rb_node; /* rb node located in rb-tree */ union { struct { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_info di; /* discard info */ }; struct list_head list; /* command list */ struct completion wait; /* compleation */ struct block_device *bdev; /* bdev */ unsigned short ref; /* reference count */ unsigned char state; /* state */ unsigned char queued; /* queued discard */ int error; /* bio error */ spinlock_t lock; /* for state/bio_ref updating */ unsigned short bio_ref; /* bio reference count */ }; enum { DPOLICY_BG, DPOLICY_FORCE, DPOLICY_FSTRIM, DPOLICY_UMOUNT, MAX_DPOLICY, }; struct discard_policy { int type; /* type of discard */ unsigned int min_interval; /* used for candidates exist */ unsigned int mid_interval; /* used for device busy */ unsigned int max_interval; /* used for candidates not exist */ unsigned int max_requests; /* # of discards issued per round */ unsigned int io_aware_gran; /* minimum granularity discard not be aware of I/O */ bool io_aware; /* issue discard in idle time */ bool sync; /* submit discard with REQ_SYNC flag */ bool ordered; /* issue discard by lba order */ unsigned int granularity; /* discard granularity */ int timeout; /* discard timeout for put_super */ }; struct discard_cmd_control { struct task_struct *f2fs_issue_discard; /* discard thread */ struct list_head entry_list; /* 4KB discard entry list */ struct list_head pend_list[MAX_PLIST_NUM];/* store pending entries */ struct list_head wait_list; /* store on-flushing entries */ struct list_head fstrim_list; /* in-flight discard from fstrim */ wait_queue_head_t discard_wait_queue; /* waiting queue for wake-up */ unsigned int discard_wake; /* to wake up discard thread */ struct mutex cmd_lock; unsigned int nr_discards; /* # of discards in the list */ unsigned int max_discards; /* max. discards to be issued */ unsigned int discard_granularity; /* discard granularity */ unsigned int undiscard_blks; /* # of undiscard blocks */ unsigned int next_pos; /* next discard position */ atomic_t issued_discard; /* # of issued discard */ atomic_t queued_discard; /* # of queued discard */ atomic_t discard_cmd_cnt; /* # of cached cmd count */ struct rb_root_cached root; /* root of discard rb-tree */ bool rbtree_check; /* config for consistence check */ }; /* for the list of fsync inodes, used only during recovery */ struct fsync_inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ block_t blkaddr; /* block address locating the last fsync */ block_t last_dentry; /* block address locating the last dentry */ }; #define nats_in_cursum(jnl) (le16_to_cpu((jnl)->n_nats)) #define sits_in_cursum(jnl) (le16_to_cpu((jnl)->n_sits)) #define nat_in_journal(jnl, i) ((jnl)->nat_j.entries[i].ne) #define nid_in_journal(jnl, i) ((jnl)->nat_j.entries[i].nid) #define sit_in_journal(jnl, i) ((jnl)->sit_j.entries[i].se) #define segno_in_journal(jnl, i) ((jnl)->sit_j.entries[i].segno) #define MAX_NAT_JENTRIES(jnl) (NAT_JOURNAL_ENTRIES - nats_in_cursum(jnl)) #define MAX_SIT_JENTRIES(jnl) (SIT_JOURNAL_ENTRIES - sits_in_cursum(jnl)) static inline int update_nats_in_cursum(struct f2fs_journal *journal, int i) { int before = nats_in_cursum(journal); journal->n_nats = cpu_to_le16(before + i); return before; } static inline int update_sits_in_cursum(struct f2fs_journal *journal, int i) { int before = sits_in_cursum(journal); journal->n_sits = cpu_to_le16(before + i); return before; } static inline bool __has_cursum_space(struct f2fs_journal *journal, int size, int type) { if (type == NAT_JOURNAL) return size <= MAX_NAT_JENTRIES(journal); return size <= MAX_SIT_JENTRIES(journal); } /* * ioctl commands */ #define F2FS_IOC_GETFLAGS FS_IOC_GETFLAGS #define F2FS_IOC_SETFLAGS FS_IOC_SETFLAGS #define F2FS_IOC_GETVERSION FS_IOC_GETVERSION #define F2FS_IOCTL_MAGIC 0xf5 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) #define F2FS_IOC_RELEASE_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 4) #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) #define F2FS_IOC_GARBAGE_COLLECT _IOW(F2FS_IOCTL_MAGIC, 6, __u32) #define F2FS_IOC_WRITE_CHECKPOINT _IO(F2FS_IOCTL_MAGIC, 7) #define F2FS_IOC_DEFRAGMENT _IOWR(F2FS_IOCTL_MAGIC, 8, \ struct f2fs_defragment) #define F2FS_IOC_MOVE_RANGE _IOWR(F2FS_IOCTL_MAGIC, 9, \ struct f2fs_move_range) #define F2FS_IOC_FLUSH_DEVICE _IOW(F2FS_IOCTL_MAGIC, 10, \ struct f2fs_flush_device) #define F2FS_IOC_GARBAGE_COLLECT_RANGE _IOW(F2FS_IOCTL_MAGIC, 11, \ struct f2fs_gc_range) #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, __u32) #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) #define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) #define F2FS_IOC_PRECACHE_EXTENTS _IO(F2FS_IOCTL_MAGIC, 15) #define F2FS_IOC_RESIZE_FS _IOW(F2FS_IOCTL_MAGIC, 16, __u64) #define F2FS_IOC_SET_ENCRYPTION_POLICY FS_IOC_SET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_POLICY FS_IOC_GET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_PWSALT FS_IOC_GET_ENCRYPTION_PWSALT /* * should be same as XFS_IOC_GOINGDOWN. * Flags for going down operation used by FS_IOC_GOINGDOWN */ #define F2FS_IOC_SHUTDOWN _IOR('X', 125, __u32) /* Shutdown */ #define F2FS_GOING_DOWN_FULLSYNC 0x0 /* going down with full sync */ #define F2FS_GOING_DOWN_METASYNC 0x1 /* going down with metadata */ #define F2FS_GOING_DOWN_NOSYNC 0x2 /* going down */ #define F2FS_GOING_DOWN_METAFLUSH 0x3 /* going down with meta flush */ #define F2FS_GOING_DOWN_NEED_FSCK 0x4 /* going down to trigger fsck */ #if defined(__KERNEL__) && defined(CONFIG_COMPAT) /* * ioctl commands in 32 bit emulation */ #define F2FS_IOC32_GETFLAGS FS_IOC32_GETFLAGS #define F2FS_IOC32_SETFLAGS FS_IOC32_SETFLAGS #define F2FS_IOC32_GETVERSION FS_IOC32_GETVERSION #endif #define F2FS_IOC_FSGETXATTR FS_IOC_FSGETXATTR #define F2FS_IOC_FSSETXATTR FS_IOC_FSSETXATTR struct f2fs_gc_range { u32 sync; u64 start; u64 len; }; struct f2fs_defragment { u64 start; u64 len; }; struct f2fs_move_range { u32 dst_fd; /* destination fd */ u64 pos_in; /* start position in src_fd */ u64 pos_out; /* start position in dst_fd */ u64 len; /* size to move */ }; struct f2fs_flush_device { u32 dev_num; /* device number to flush */ u32 segments; /* # of segments to flush */ }; /* for inline stuff */ #define DEF_INLINE_RESERVED_SIZE 1 static inline int get_extra_isize(struct inode *inode); static inline int get_inline_xattr_addrs(struct inode *inode); #define MAX_INLINE_DATA(inode) (sizeof(__le32) * \ (CUR_ADDRS_PER_INODE(inode) - \ get_inline_xattr_addrs(inode) - \ DEF_INLINE_RESERVED_SIZE)) /* for inline dir */ #define NR_INLINE_DENTRY(inode) (MAX_INLINE_DATA(inode) * BITS_PER_BYTE / \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ BITS_PER_BYTE + 1)) #define INLINE_DENTRY_BITMAP_SIZE(inode) \ DIV_ROUND_UP(NR_INLINE_DENTRY(inode), BITS_PER_BYTE) #define INLINE_RESERVED_SIZE(inode) (MAX_INLINE_DATA(inode) - \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ NR_INLINE_DENTRY(inode) + \ INLINE_DENTRY_BITMAP_SIZE(inode))) /* * For INODE and NODE manager */ /* for directory operations */ struct f2fs_dentry_ptr { struct inode *inode; void *bitmap; struct f2fs_dir_entry *dentry; __u8 (*filename)[F2FS_SLOT_LEN]; int max; int nr_bitmap; }; static inline void make_dentry_ptr_block(struct inode *inode, struct f2fs_dentry_ptr *d, struct f2fs_dentry_block *t) { d->inode = inode; d->max = NR_DENTRY_IN_BLOCK; d->nr_bitmap = SIZE_OF_DENTRY_BITMAP; d->bitmap = t->dentry_bitmap; d->dentry = t->dentry; d->filename = t->filename; } static inline void make_dentry_ptr_inline(struct inode *inode, struct f2fs_dentry_ptr *d, void *t) { int entry_cnt = NR_INLINE_DENTRY(inode); int bitmap_size = INLINE_DENTRY_BITMAP_SIZE(inode); int reserved_size = INLINE_RESERVED_SIZE(inode); d->inode = inode; d->max = entry_cnt; d->nr_bitmap = bitmap_size; d->bitmap = t; d->dentry = t + bitmap_size + reserved_size; d->filename = t + bitmap_size + reserved_size + SIZE_OF_DIR_ENTRY * entry_cnt; } /* * XATTR_NODE_OFFSET stores xattrs to one node block per file keeping -1 * as its node offset to distinguish from index node blocks. * But some bits are used to mark the node block. */ #define XATTR_NODE_OFFSET ((((unsigned int)-1) << OFFSET_BIT_SHIFT) \ >> OFFSET_BIT_SHIFT) enum { ALLOC_NODE, /* allocate a new node page if needed */ LOOKUP_NODE, /* look up a node without readahead */ LOOKUP_NODE_RA, /* * look up a node with readahead called * by get_data_block. */ }; #define DEFAULT_RETRY_IO_COUNT 8 /* maximum retry read IO count */ /* maximum retry quota flush count */ #define DEFAULT_RETRY_QUOTA_FLUSH_COUNT 8 #define F2FS_LINK_MAX 0xffffffff /* maximum link count per file */ #define MAX_DIR_RA_PAGES 4 /* maximum ra pages of dir */ /* for in-memory extent cache entry */ #define F2FS_MIN_EXTENT_LEN 64 /* minimum extent length */ /* number of extent info in extent cache we try to shrink */ #define EXTENT_CACHE_SHRINK_NUMBER 128 struct rb_entry { struct rb_node rb_node; /* rb node located in rb-tree */ unsigned int ofs; /* start offset of the entry */ unsigned int len; /* length of the entry */ }; struct extent_info { unsigned int fofs; /* start offset in a file */ unsigned int len; /* length of the extent */ u32 blk; /* start block address of the extent */ }; struct extent_node { struct rb_node rb_node; /* rb node located in rb-tree */ struct extent_info ei; /* extent info */ struct list_head list; /* node in global extent list of sbi */ struct extent_tree *et; /* extent tree pointer */ }; struct extent_tree { nid_t ino; /* inode number */ struct rb_root_cached root; /* root of extent info rb-tree */ struct extent_node *cached_en; /* recently accessed extent node */ struct extent_info largest; /* largested extent info */ struct list_head list; /* to be used by sbi->zombie_list */ rwlock_t lock; /* protect extent info rb-tree */ atomic_t node_cnt; /* # of extent node in rb-tree*/ bool largest_updated; /* largest extent updated */ }; /* * This structure is taken from ext4_map_blocks. * * Note that, however, f2fs uses NEW and MAPPED flags for f2fs_map_blocks(). */ #define F2FS_MAP_NEW (1 << BH_New) #define F2FS_MAP_MAPPED (1 << BH_Mapped) #define F2FS_MAP_UNWRITTEN (1 << BH_Unwritten) #define F2FS_MAP_FLAGS (F2FS_MAP_NEW | F2FS_MAP_MAPPED |\ F2FS_MAP_UNWRITTEN) struct f2fs_map_blocks { block_t m_pblk; block_t m_lblk; unsigned int m_len; unsigned int m_flags; pgoff_t *m_next_pgofs; /* point next possible non-hole pgofs */ pgoff_t *m_next_extent; /* point to next possible extent */ int m_seg_type; bool m_may_create; /* indicate it is from write path */ }; /* for flag in get_data_block */ enum { F2FS_GET_BLOCK_DEFAULT, F2FS_GET_BLOCK_FIEMAP, F2FS_GET_BLOCK_BMAP, F2FS_GET_BLOCK_DIO, F2FS_GET_BLOCK_PRE_DIO, F2FS_GET_BLOCK_PRE_AIO, F2FS_GET_BLOCK_PRECACHE, }; /* * i_advise uses FADVISE_XXX_BIT. We can add additional hints later. */ #define FADVISE_COLD_BIT 0x01 #define FADVISE_LOST_PINO_BIT 0x02 #define FADVISE_ENCRYPT_BIT 0x04 #define FADVISE_ENC_NAME_BIT 0x08 #define FADVISE_KEEP_SIZE_BIT 0x10 #define FADVISE_HOT_BIT 0x20 #define FADVISE_VERITY_BIT 0x40 /* reserved */ #define FADVISE_MODIFIABLE_BITS (FADVISE_COLD_BIT | FADVISE_HOT_BIT) #define file_is_cold(inode) is_file(inode, FADVISE_COLD_BIT) #define file_wrong_pino(inode) is_file(inode, FADVISE_LOST_PINO_BIT) #define file_set_cold(inode) set_file(inode, FADVISE_COLD_BIT) #define file_lost_pino(inode) set_file(inode, FADVISE_LOST_PINO_BIT) #define file_clear_cold(inode) clear_file(inode, FADVISE_COLD_BIT) #define file_got_pino(inode) clear_file(inode, FADVISE_LOST_PINO_BIT) #define file_is_encrypt(inode) is_file(inode, FADVISE_ENCRYPT_BIT) #define file_set_encrypt(inode) set_file(inode, FADVISE_ENCRYPT_BIT) #define file_clear_encrypt(inode) clear_file(inode, FADVISE_ENCRYPT_BIT) #define file_enc_name(inode) is_file(inode, FADVISE_ENC_NAME_BIT) #define file_set_enc_name(inode) set_file(inode, FADVISE_ENC_NAME_BIT) #define file_keep_isize(inode) is_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_set_keep_isize(inode) set_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_is_hot(inode) is_file(inode, FADVISE_HOT_BIT) #define file_set_hot(inode) set_file(inode, FADVISE_HOT_BIT) #define file_clear_hot(inode) clear_file(inode, FADVISE_HOT_BIT) #define DEF_DIR_LEVEL 0 enum { GC_FAILURE_PIN, GC_FAILURE_ATOMIC, MAX_GC_FAILURE }; struct f2fs_inode_info { struct inode vfs_inode; /* serve a vfs inode */ unsigned long i_flags; /* keep an inode flags for ioctl */ unsigned char i_advise; /* use to give file attribute hints */ unsigned char i_dir_level; /* use for dentry level for large dir */ unsigned int i_current_depth; /* only for directory depth */ /* for gc failure statistic */ unsigned int i_gc_failures[MAX_GC_FAILURE]; unsigned int i_pino; /* parent inode number */ umode_t i_acl_mode; /* keep file acl mode temporarily */ /* Use below internally in f2fs*/ unsigned long flags; /* use to pass per-file flags */ struct rw_semaphore i_sem; /* protect fi info */ atomic_t dirty_pages; /* # of dirty pages */ f2fs_hash_t chash; /* hash value of given file name */ unsigned int clevel; /* maximum level of given file name */ struct task_struct *task; /* lookup and create consistency */ struct task_struct *cp_task; /* separate cp/wb IO stats*/ nid_t i_xattr_nid; /* node id that contains xattrs */ loff_t last_disk_size; /* lastly written file size */ #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; /* quota space reservation, managed internally by quota code */ qsize_t i_reserved_quota; #endif struct list_head dirty_list; /* dirty list for dirs and files */ struct list_head gdirty_list; /* linked in global dirty list */ struct list_head inmem_ilist; /* list for inmem inodes */ struct list_head inmem_pages; /* inmemory pages managed by f2fs */ struct task_struct *inmem_task; /* store inmemory task */ struct mutex inmem_lock; /* lock for inmemory pages */ struct extent_tree *extent_tree; /* cached extent_tree entry */ /* avoid racing between foreground op and gc */ struct rw_semaphore i_gc_rwsem[2]; struct rw_semaphore i_mmap_sem; struct rw_semaphore i_xattr_sem; /* avoid racing between reading and changing EAs */ int i_extra_isize; /* size of extra space located in i_addr */ kprojid_t i_projid; /* id for project quota */ int i_inline_xattr_size; /* inline xattr size */ struct timespec64 i_crtime; /* inode creation time */ struct timespec64 i_disk_time[4];/* inode disk times */ }; static inline void get_extent_info(struct extent_info *ext, struct f2fs_extent *i_ext) { ext->fofs = le32_to_cpu(i_ext->fofs); ext->blk = le32_to_cpu(i_ext->blk); ext->len = le32_to_cpu(i_ext->len); } static inline void set_raw_extent(struct extent_info *ext, struct f2fs_extent *i_ext) { i_ext->fofs = cpu_to_le32(ext->fofs); i_ext->blk = cpu_to_le32(ext->blk); i_ext->len = cpu_to_le32(ext->len); } static inline void set_extent_info(struct extent_info *ei, unsigned int fofs, u32 blk, unsigned int len) { ei->fofs = fofs; ei->blk = blk; ei->len = len; } static inline bool __is_discard_mergeable(struct discard_info *back, struct discard_info *front, unsigned int max_len) { return (back->lstart + back->len == front->lstart) && (back->len + front->len <= max_len); } static inline bool __is_discard_back_mergeable(struct discard_info *cur, struct discard_info *back, unsigned int max_len) { return __is_discard_mergeable(back, cur, max_len); } static inline bool __is_discard_front_mergeable(struct discard_info *cur, struct discard_info *front, unsigned int max_len) { return __is_discard_mergeable(cur, front, max_len); } static inline bool __is_extent_mergeable(struct extent_info *back, struct extent_info *front) { return (back->fofs + back->len == front->fofs && back->blk + back->len == front->blk); } static inline bool __is_back_mergeable(struct extent_info *cur, struct extent_info *back) { return __is_extent_mergeable(back, cur); } static inline bool __is_front_mergeable(struct extent_info *cur, struct extent_info *front) { return __is_extent_mergeable(cur, front); } extern void f2fs_mark_inode_dirty_sync(struct inode *inode, bool sync); static inline void __try_update_largest_extent(struct extent_tree *et, struct extent_node *en) { if (en->ei.len > et->largest.len) { et->largest = en->ei; et->largest_updated = true; } } /* * For free nid management */ enum nid_state { FREE_NID, /* newly added to free nid list */ PREALLOC_NID, /* it is preallocated */ MAX_NID_STATE, }; struct f2fs_nm_info { block_t nat_blkaddr; /* base disk address of NAT */ nid_t max_nid; /* maximum possible node ids */ nid_t available_nids; /* # of available node ids */ nid_t next_scan_nid; /* the next nid to be scanned */ unsigned int ram_thresh; /* control the memory footprint */ unsigned int ra_nid_pages; /* # of nid pages to be readaheaded */ unsigned int dirty_nats_ratio; /* control dirty nats ratio threshold */ /* NAT cache management */ struct radix_tree_root nat_root;/* root of the nat entry cache */ struct radix_tree_root nat_set_root;/* root of the nat set cache */ struct rw_semaphore nat_tree_lock; /* protect nat_tree_lock */ struct list_head nat_entries; /* cached nat entry list (clean) */ spinlock_t nat_list_lock; /* protect clean nat entry list */ unsigned int nat_cnt; /* the # of cached nat entries */ unsigned int dirty_nat_cnt; /* total num of nat entries in set */ unsigned int nat_blocks; /* # of nat blocks */ /* free node ids management */ struct radix_tree_root free_nid_root;/* root of the free_nid cache */ struct list_head free_nid_list; /* list for free nids excluding preallocated nids */ unsigned int nid_cnt[MAX_NID_STATE]; /* the number of free node id */ spinlock_t nid_list_lock; /* protect nid lists ops */ struct mutex build_lock; /* lock for build free nids */ unsigned char **free_nid_bitmap; unsigned char *nat_block_bitmap; unsigned short *free_nid_count; /* free nid count of NAT block */ /* for checkpoint */ char *nat_bitmap; /* NAT bitmap pointer */ unsigned int nat_bits_blocks; /* # of nat bits blocks */ unsigned char *nat_bits; /* NAT bits blocks */ unsigned char *full_nat_bits; /* full NAT pages */ unsigned char *empty_nat_bits; /* empty NAT pages */ #ifdef CONFIG_F2FS_CHECK_FS char *nat_bitmap_mir; /* NAT bitmap mirror */ #endif int bitmap_size; /* bitmap size */ }; /* * this structure is used as one of function parameters. * all the information are dedicated to a given direct node block determined * by the data offset in a file. */ struct dnode_of_data { struct inode *inode; /* vfs inode pointer */ struct page *inode_page; /* its inode page, NULL is possible */ struct page *node_page; /* cached direct node page */ nid_t nid; /* node id of the direct node block */ unsigned int ofs_in_node; /* data offset in the node page */ bool inode_page_locked; /* inode page is locked or not */ bool node_changed; /* is node block changed */ char cur_level; /* level of hole node page */ char max_level; /* level of current page located */ block_t data_blkaddr; /* block address of the node block */ }; static inline void set_new_dnode(struct dnode_of_data *dn, struct inode *inode, struct page *ipage, struct page *npage, nid_t nid) { memset(dn, 0, sizeof(*dn)); dn->inode = inode; dn->inode_page = ipage; dn->node_page = npage; dn->nid = nid; } /* * For SIT manager * * By default, there are 6 active log areas across the whole main area. * When considering hot and cold data separation to reduce cleaning overhead, * we split 3 for data logs and 3 for node logs as hot, warm, and cold types, * respectively. * In the current design, you should not change the numbers intentionally. * Instead, as a mount option such as active_logs=x, you can use 2, 4, and 6 * logs individually according to the underlying devices. (default: 6) * Just in case, on-disk layout covers maximum 16 logs that consist of 8 for * data and 8 for node logs. */ #define NR_CURSEG_DATA_TYPE (3) #define NR_CURSEG_NODE_TYPE (3) #define NR_CURSEG_TYPE (NR_CURSEG_DATA_TYPE + NR_CURSEG_NODE_TYPE) enum { CURSEG_HOT_DATA = 0, /* directory entry blocks */ CURSEG_WARM_DATA, /* data blocks */ CURSEG_COLD_DATA, /* multimedia or GCed data blocks */ CURSEG_HOT_NODE, /* direct node blocks of directory files */ CURSEG_WARM_NODE, /* direct node blocks of normal files */ CURSEG_COLD_NODE, /* indirect node blocks */ NO_CHECK_TYPE, }; struct flush_cmd { struct completion wait; struct llist_node llnode; nid_t ino; int ret; }; struct flush_cmd_control { struct task_struct *f2fs_issue_flush; /* flush thread */ wait_queue_head_t flush_wait_queue; /* waiting queue for wake-up */ atomic_t issued_flush; /* # of issued flushes */ atomic_t queued_flush; /* # of queued flushes */ struct llist_head issue_list; /* list for command issue */ struct llist_node *dispatch_list; /* list for command dispatch */ }; struct f2fs_sm_info { struct sit_info *sit_info; /* whole segment information */ struct free_segmap_info *free_info; /* free segment information */ struct dirty_seglist_info *dirty_info; /* dirty segment information */ struct curseg_info *curseg_array; /* active segment information */ struct rw_semaphore curseg_lock; /* for preventing curseg change */ block_t seg0_blkaddr; /* block address of 0'th segment */ block_t main_blkaddr; /* start block address of main area */ block_t ssa_blkaddr; /* start block address of SSA area */ unsigned int segment_count; /* total # of segments */ unsigned int main_segments; /* # of segments in main area */ unsigned int reserved_segments; /* # of reserved segments */ unsigned int ovp_segments; /* # of overprovision segments */ /* a threshold to reclaim prefree segments */ unsigned int rec_prefree_segments; /* for batched trimming */ unsigned int trim_sections; /* # of sections to trim */ struct list_head sit_entry_set; /* sit entry set list */ unsigned int ipu_policy; /* in-place-update policy */ unsigned int min_ipu_util; /* in-place-update threshold */ unsigned int min_fsync_blocks; /* threshold for fsync */ unsigned int min_seq_blocks; /* threshold for sequential blocks */ unsigned int min_hot_blocks; /* threshold for hot block allocation */ unsigned int min_ssr_sections; /* threshold to trigger SSR allocation */ /* for flush command control */ struct flush_cmd_control *fcc_info; /* for discard command control */ struct discard_cmd_control *dcc_info; }; /* * For superblock */ /* * COUNT_TYPE for monitoring * * f2fs monitors the number of several block types such as on-writeback, * dirty dentry blocks, dirty node blocks, and dirty meta blocks. */ #define WB_DATA_TYPE(p) (__is_cp_guaranteed(p) ? F2FS_WB_CP_DATA : F2FS_WB_DATA) enum count_type { F2FS_DIRTY_DENTS, F2FS_DIRTY_DATA, F2FS_DIRTY_QDATA, F2FS_DIRTY_NODES, F2FS_DIRTY_META, F2FS_INMEM_PAGES, F2FS_DIRTY_IMETA, F2FS_WB_CP_DATA, F2FS_WB_DATA, F2FS_RD_DATA, F2FS_RD_NODE, F2FS_RD_META, F2FS_DIO_WRITE, F2FS_DIO_READ, NR_COUNT_TYPE, }; /* * The below are the page types of bios used in submit_bio(). * The available types are: * DATA User data pages. It operates as async mode. * NODE Node pages. It operates as async mode. * META FS metadata pages such as SIT, NAT, CP. * NR_PAGE_TYPE The number of page types. * META_FLUSH Make sure the previous pages are written * with waiting the bio's completion * ... Only can be used with META. */ #define PAGE_TYPE_OF_BIO(type) ((type) > META ? META : (type)) enum page_type { DATA, NODE, META, NR_PAGE_TYPE, META_FLUSH, INMEM, /* the below types are used by tracepoints only. */ INMEM_DROP, INMEM_INVALIDATE, INMEM_REVOKE, IPU, OPU, }; enum temp_type { HOT = 0, /* must be zero for meta bio */ WARM, COLD, NR_TEMP_TYPE, }; enum need_lock_type { LOCK_REQ = 0, LOCK_DONE, LOCK_RETRY, }; enum cp_reason_type { CP_NO_NEEDED, CP_NON_REGULAR, CP_HARDLINK, CP_SB_NEED_CP, CP_WRONG_PINO, CP_NO_SPC_ROLL, CP_NODE_NEED_CP, CP_FASTBOOT_MODE, CP_SPEC_LOG_NUM, CP_RECOVER_DIR, }; enum iostat_type { APP_DIRECT_IO, /* app direct IOs */ APP_BUFFERED_IO, /* app buffered IOs */ APP_WRITE_IO, /* app write IOs */ APP_MAPPED_IO, /* app mapped IOs */ FS_DATA_IO, /* data IOs from kworker/fsync/reclaimer */ FS_NODE_IO, /* node IOs from kworker/fsync/reclaimer */ FS_META_IO, /* meta IOs from kworker/reclaimer */ FS_GC_DATA_IO, /* data IOs from forground gc */ FS_GC_NODE_IO, /* node IOs from forground gc */ FS_CP_DATA_IO, /* data IOs from checkpoint */ FS_CP_NODE_IO, /* node IOs from checkpoint */ FS_CP_META_IO, /* meta IOs from checkpoint */ FS_DISCARD, /* discard */ NR_IO_TYPE, }; struct f2fs_io_info { struct f2fs_sb_info *sbi; /* f2fs_sb_info pointer */ nid_t ino; /* inode number */ enum page_type type; /* contains DATA/NODE/META/META_FLUSH */ enum temp_type temp; /* contains HOT/WARM/COLD */ int op; /* contains REQ_OP_ */ int op_flags; /* req_flag_bits */ block_t new_blkaddr; /* new block address to be written */ block_t old_blkaddr; /* old block address before Cow */ struct page *page; /* page to be written */ struct page *encrypted_page; /* encrypted page */ struct list_head list; /* serialize IOs */ bool submitted; /* indicate IO submission */ int need_lock; /* indicate we need to lock cp_rwsem */ bool in_list; /* indicate fio is in io_list */ bool is_por; /* indicate IO is from recovery or not */ bool retry; /* need to reallocate block address */ enum iostat_type io_type; /* io type */ struct writeback_control *io_wbc; /* writeback control */ struct bio **bio; /* bio for ipu */ sector_t *last_block; /* last block number in bio */ unsigned char version; /* version of the node */ }; #define is_read_io(rw) ((rw) == READ) struct f2fs_bio_info { struct f2fs_sb_info *sbi; /* f2fs superblock */ struct bio *bio; /* bios to merge */ sector_t last_block_in_bio; /* last block number */ struct f2fs_io_info fio; /* store buffered io info. */ struct rw_semaphore io_rwsem; /* blocking op for bio */ spinlock_t io_lock; /* serialize DATA/NODE IOs */ struct list_head io_list; /* track fios */ }; #define FDEV(i) (sbi->devs[i]) #define RDEV(i) (raw_super->devs[i]) struct f2fs_dev_info { struct block_device *bdev; char path[MAX_PATH_LEN]; unsigned int total_segments; block_t start_blk; block_t end_blk; #ifdef CONFIG_BLK_DEV_ZONED unsigned int nr_blkz; /* Total number of zones */ unsigned long *blkz_seq; /* Bitmap indicating sequential zones */ #endif }; enum inode_type { DIR_INODE, /* for dirty dir inode */ FILE_INODE, /* for dirty regular/symlink inode */ DIRTY_META, /* for all dirtied inode metadata */ ATOMIC_FILE, /* for all atomic files */ NR_INODE_TYPE, }; /* for inner inode cache management */ struct inode_management { struct radix_tree_root ino_root; /* ino entry array */ spinlock_t ino_lock; /* for ino entry lock */ struct list_head ino_list; /* inode list head */ unsigned long ino_num; /* number of entries */ }; /* For s_flag in struct f2fs_sb_info */ enum { SBI_IS_DIRTY, /* dirty flag for checkpoint */ SBI_IS_CLOSE, /* specify unmounting */ SBI_NEED_FSCK, /* need fsck.f2fs to fix */ SBI_POR_DOING, /* recovery is doing or not */ SBI_NEED_SB_WRITE, /* need to recover superblock */ SBI_NEED_CP, /* need to checkpoint */ SBI_IS_SHUTDOWN, /* shutdown by ioctl */ SBI_IS_RECOVERED, /* recovered orphan/data */ SBI_CP_DISABLED, /* CP was disabled last mount */ SBI_CP_DISABLED_QUICK, /* CP was disabled quickly */ SBI_QUOTA_NEED_FLUSH, /* need to flush quota info in CP */ SBI_QUOTA_SKIP_FLUSH, /* skip flushing quota in current CP */ SBI_QUOTA_NEED_REPAIR, /* quota file may be corrupted */ SBI_IS_RESIZEFS, /* resizefs is in process */ }; enum { CP_TIME, REQ_TIME, DISCARD_TIME, GC_TIME, DISABLE_TIME, UMOUNT_DISCARD_TIMEOUT, MAX_TIME, }; enum { GC_NORMAL, GC_IDLE_CB, GC_IDLE_GREEDY, GC_URGENT, }; enum { WHINT_MODE_OFF, /* not pass down write hints */ WHINT_MODE_USER, /* try to pass down hints given by users */ WHINT_MODE_FS, /* pass down hints with F2FS policy */ }; enum { ALLOC_MODE_DEFAULT, /* stay default */ ALLOC_MODE_REUSE, /* reuse segments as much as possible */ }; enum fsync_mode { FSYNC_MODE_POSIX, /* fsync follows posix semantics */ FSYNC_MODE_STRICT, /* fsync behaves in line with ext4 */ FSYNC_MODE_NOBARRIER, /* fsync behaves nobarrier based on posix */ }; #ifdef CONFIG_FS_ENCRYPTION #define DUMMY_ENCRYPTION_ENABLED(sbi) \ (unlikely(F2FS_OPTION(sbi).test_dummy_encryption)) #else #define DUMMY_ENCRYPTION_ENABLED(sbi) (0) #endif struct f2fs_sb_info { struct super_block *sb; /* pointer to VFS super block */ struct proc_dir_entry *s_proc; /* proc entry */ struct f2fs_super_block *raw_super; /* raw super block pointer */ struct rw_semaphore sb_lock; /* lock for raw super block */ int valid_super_block; /* valid super block no */ unsigned long s_flag; /* flags for sbi */ struct mutex writepages; /* mutex for writepages() */ #ifdef CONFIG_BLK_DEV_ZONED unsigned int blocks_per_blkz; /* F2FS blocks per zone */ unsigned int log_blocks_per_blkz; /* log2 F2FS blocks per zone */ #endif /* for node-related operations */ struct f2fs_nm_info *nm_info; /* node manager */ struct inode *node_inode; /* cache node blocks */ /* for segment-related operations */ struct f2fs_sm_info *sm_info; /* segment manager */ /* for bio operations */ struct f2fs_bio_info *write_io[NR_PAGE_TYPE]; /* for write bios */ /* keep migration IO order for LFS mode */ struct rw_semaphore io_order_lock; mempool_t *write_io_dummy; /* Dummy pages */ /* for checkpoint */ struct f2fs_checkpoint *ckpt; /* raw checkpoint pointer */ int cur_cp_pack; /* remain current cp pack */ spinlock_t cp_lock; /* for flag in ckpt */ struct inode *meta_inode; /* cache meta blocks */ struct mutex cp_mutex; /* checkpoint procedure lock */ struct rw_semaphore cp_rwsem; /* blocking FS operations */ struct rw_semaphore node_write; /* locking node writes */ struct rw_semaphore node_change; /* locking node change */ wait_queue_head_t cp_wait; unsigned long last_time[MAX_TIME]; /* to store time in jiffies */ long interval_time[MAX_TIME]; /* to store thresholds */ struct inode_management im[MAX_INO_ENTRY]; /* manage inode cache */ spinlock_t fsync_node_lock; /* for node entry lock */ struct list_head fsync_node_list; /* node list head */ unsigned int fsync_seg_id; /* sequence id */ unsigned int fsync_node_num; /* number of node entries */ /* for orphan inode, use 0'th array */ unsigned int max_orphans; /* max orphan inodes */ /* for inode management */ struct list_head inode_list[NR_INODE_TYPE]; /* dirty inode list */ spinlock_t inode_lock[NR_INODE_TYPE]; /* for dirty inode list lock */ struct mutex flush_lock; /* for flush exclusion */ /* for extent tree cache */ struct radix_tree_root extent_tree_root;/* cache extent cache entries */ struct mutex extent_tree_lock; /* locking extent radix tree */ struct list_head extent_list; /* lru list for shrinker */ spinlock_t extent_lock; /* locking extent lru list */ atomic_t total_ext_tree; /* extent tree count */ struct list_head zombie_list; /* extent zombie tree list */ atomic_t total_zombie_tree; /* extent zombie tree count */ atomic_t total_ext_node; /* extent info count */ /* basic filesystem units */ unsigned int log_sectors_per_block; /* log2 sectors per block */ unsigned int log_blocksize; /* log2 block size */ unsigned int blocksize; /* block size */ unsigned int root_ino_num; /* root inode number*/ unsigned int node_ino_num; /* node inode number*/ unsigned int meta_ino_num; /* meta inode number*/ unsigned int log_blocks_per_seg; /* log2 blocks per segment */ unsigned int blocks_per_seg; /* blocks per segment */ unsigned int segs_per_sec; /* segments per section */ unsigned int secs_per_zone; /* sections per zone */ unsigned int total_sections; /* total section count */ struct mutex resize_mutex; /* for resize exclusion */ unsigned int total_node_count; /* total node block count */ unsigned int total_valid_node_count; /* valid node block count */ loff_t max_file_blocks; /* max block index of file */ int dir_level; /* directory level */ int readdir_ra; /* readahead inode in readdir */ block_t user_block_count; /* # of user blocks */ block_t total_valid_block_count; /* # of valid blocks */ block_t discard_blks; /* discard command candidats */ block_t last_valid_block_count; /* for recovery */ block_t reserved_blocks; /* configurable reserved blocks */ block_t current_reserved_blocks; /* current reserved blocks */ /* Additional tracking for no checkpoint mode */ block_t unusable_block_count; /* # of blocks saved by last cp */ unsigned int nquota_files; /* # of quota sysfile */ struct rw_semaphore quota_sem; /* blocking cp for flags */ /* # of pages, see count_type */ atomic_t nr_pages[NR_COUNT_TYPE]; /* # of allocated blocks */ struct percpu_counter alloc_valid_block_count; /* writeback control */ atomic_t wb_sync_req[META]; /* count # of WB_SYNC threads */ /* valid inode count */ struct percpu_counter total_valid_inode_count; struct f2fs_mount_info mount_opt; /* mount options */ /* for cleaning operations */ struct mutex gc_mutex; /* mutex for GC */ struct f2fs_gc_kthread *gc_thread; /* GC thread */ unsigned int cur_victim_sec; /* current victim section num */ unsigned int gc_mode; /* current GC state */ unsigned int next_victim_seg[2]; /* next segment in victim section */ /* for skip statistic */ unsigned long long skipped_atomic_files[2]; /* FG_GC and BG_GC */ unsigned long long skipped_gc_rwsem; /* FG_GC only */ /* threshold for gc trials on pinned files */ u64 gc_pin_file_threshold; /* maximum # of trials to find a victim segment for SSR and GC */ unsigned int max_victim_search; /* migration granularity of garbage collection, unit: segment */ unsigned int migration_granularity; /* * for stat information. * one is for the LFS mode, and the other is for the SSR mode. */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info *stat_info; /* FS status information */ atomic_t meta_count[META_MAX]; /* # of meta blocks */ unsigned int segment_count[2]; /* # of allocated segments */ unsigned int block_count[2]; /* # of allocated blocks */ atomic_t inplace_count; /* # of inplace update */ atomic64_t total_hit_ext; /* # of lookup extent cache */ atomic64_t read_hit_rbtree; /* # of hit rbtree extent node */ atomic64_t read_hit_largest; /* # of hit largest extent node */ atomic64_t read_hit_cached; /* # of hit cached extent node */ atomic_t inline_xattr; /* # of inline_xattr inodes */ atomic_t inline_inode; /* # of inline_data inodes */ atomic_t inline_dir; /* # of inline_dentry inodes */ atomic_t aw_cnt; /* # of atomic writes */ atomic_t vw_cnt; /* # of volatile writes */ atomic_t max_aw_cnt; /* max # of atomic writes */ atomic_t max_vw_cnt; /* max # of volatile writes */ int bg_gc; /* background gc calls */ unsigned int io_skip_bggc; /* skip background gc for in-flight IO */ unsigned int other_skip_bggc; /* skip background gc for other reasons */ unsigned int ndirty_inode[NR_INODE_TYPE]; /* # of dirty inodes */ #endif spinlock_t stat_lock; /* lock for stat operations */ /* For app/fs IO statistics */ spinlock_t iostat_lock; unsigned long long write_iostat[NR_IO_TYPE]; bool iostat_enable; /* For sysfs suppport */ struct kobject s_kobj; struct completion s_kobj_unregister; /* For shrinker support */ struct list_head s_list; int s_ndevs; /* number of devices */ struct f2fs_dev_info *devs; /* for device list */ unsigned int dirty_device; /* for checkpoint data flush */ spinlock_t dev_lock; /* protect dirty_device */ struct mutex umount_mutex; unsigned int shrinker_run_no; /* For write statistics */ u64 sectors_written_start; u64 kbytes_written; /* Reference to checksum algorithm driver via cryptoapi */ struct crypto_shash *s_chksum_driver; /* Precomputed FS UUID checksum for seeding other checksums */ __u32 s_chksum_seed; }; struct f2fs_private_dio { struct inode *inode; void *orig_private; bio_end_io_t *orig_end_io; bool write; }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define f2fs_show_injection_info(type) \ printk_ratelimited("%sF2FS-fs : inject %s in %s of %pS\n", \ KERN_INFO, f2fs_fault_name[type], \ __func__, __builtin_return_address(0)) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info; if (!ffi->inject_rate) return false; if (!IS_FAULT_SET(ffi, type)) return false; atomic_inc(&ffi->inject_ops); if (atomic_read(&ffi->inject_ops) >= ffi->inject_rate) { atomic_set(&ffi->inject_ops, 0); return true; } return false; } #else #define f2fs_show_injection_info(type) do { } while (0) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { return false; } #endif /* * Test if the mounted volume is a multi-device volume. * - For a single regular disk volume, sbi->s_ndevs is 0. * - For a single zoned disk volume, sbi->s_ndevs is 1. * - For a multi-device volume, sbi->s_ndevs is always 2 or more. */ static inline bool f2fs_is_multi_device(struct f2fs_sb_info *sbi) { return sbi->s_ndevs > 1; } /* For write statistics. Suppose sector size is 512 bytes, * and the return value is in kbytes. s is of struct f2fs_sb_info. */ #define BD_PART_WRITTEN(s) \ (((u64)part_stat_read((s)->sb->s_bdev->bd_part, sectors[STAT_WRITE]) - \ (s)->sectors_written_start) >> 1) static inline void f2fs_update_time(struct f2fs_sb_info *sbi, int type) { unsigned long now = jiffies; sbi->last_time[type] = now; /* DISCARD_TIME and GC_TIME are based on REQ_TIME */ if (type == REQ_TIME) { sbi->last_time[DISCARD_TIME] = now; sbi->last_time[GC_TIME] = now; } } static inline bool f2fs_time_over(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; return time_after(jiffies, sbi->last_time[type] + interval); } static inline unsigned int f2fs_time_to_wait(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; unsigned int wait_ms = 0; long delta; delta = (sbi->last_time[type] + interval) - jiffies; if (delta > 0) wait_ms = jiffies_to_msecs(delta); return wait_ms; } /* * Inline functions */ static inline u32 __f2fs_crc32(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { struct { struct shash_desc shash; char ctx[4]; } desc; int err; BUG_ON(crypto_shash_descsize(sbi->s_chksum_driver) != sizeof(desc.ctx)); desc.shash.tfm = sbi->s_chksum_driver; *(u32 *)desc.ctx = crc; err = crypto_shash_update(&desc.shash, address, length); BUG_ON(err); return *(u32 *)desc.ctx; } static inline u32 f2fs_crc32(struct f2fs_sb_info *sbi, const void *address, unsigned int length) { return __f2fs_crc32(sbi, F2FS_SUPER_MAGIC, address, length); } static inline bool f2fs_crc_valid(struct f2fs_sb_info *sbi, __u32 blk_crc, void *buf, size_t buf_size) { return f2fs_crc32(sbi, buf, buf_size) == blk_crc; } static inline u32 f2fs_chksum(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { return __f2fs_crc32(sbi, crc, address, length); } static inline struct f2fs_inode_info *F2FS_I(struct inode *inode) { return container_of(inode, struct f2fs_inode_info, vfs_inode); } static inline struct f2fs_sb_info *F2FS_SB(struct super_block *sb) { return sb->s_fs_info; } static inline struct f2fs_sb_info *F2FS_I_SB(struct inode *inode) { return F2FS_SB(inode->i_sb); } static inline struct f2fs_sb_info *F2FS_M_SB(struct address_space *mapping) { return F2FS_I_SB(mapping->host); } static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page->mapping); } static inline struct f2fs_super_block *F2FS_RAW_SUPER(struct f2fs_sb_info *sbi) { return (struct f2fs_super_block *)(sbi->raw_super); } static inline struct f2fs_checkpoint *F2FS_CKPT(struct f2fs_sb_info *sbi) { return (struct f2fs_checkpoint *)(sbi->ckpt); } static inline struct f2fs_node *F2FS_NODE(struct page *page) { return (struct f2fs_node *)page_address(page); } static inline struct f2fs_inode *F2FS_INODE(struct page *page) { return &((struct f2fs_node *)page_address(page))->i; } static inline struct f2fs_nm_info *NM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_nm_info *)(sbi->nm_info); } static inline struct f2fs_sm_info *SM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_sm_info *)(sbi->sm_info); } static inline struct sit_info *SIT_I(struct f2fs_sb_info *sbi) { return (struct sit_info *)(SM_I(sbi)->sit_info); } static inline struct free_segmap_info *FREE_I(struct f2fs_sb_info *sbi) { return (struct free_segmap_info *)(SM_I(sbi)->free_info); } static inline struct dirty_seglist_info *DIRTY_I(struct f2fs_sb_info *sbi) { return (struct dirty_seglist_info *)(SM_I(sbi)->dirty_info); } static inline struct address_space *META_MAPPING(struct f2fs_sb_info *sbi) { return sbi->meta_inode->i_mapping; } static inline struct address_space *NODE_MAPPING(struct f2fs_sb_info *sbi) { return sbi->node_inode->i_mapping; } static inline bool is_sbi_flag_set(struct f2fs_sb_info *sbi, unsigned int type) { return test_bit(type, &sbi->s_flag); } static inline void set_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { set_bit(type, &sbi->s_flag); } static inline void clear_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { clear_bit(type, &sbi->s_flag); } static inline unsigned long long cur_cp_version(struct f2fs_checkpoint *cp) { return le64_to_cpu(cp->checkpoint_ver); } static inline unsigned long f2fs_qf_ino(struct super_block *sb, int type) { if (type < F2FS_MAX_QUOTAS) return le32_to_cpu(F2FS_SB(sb)->raw_super->qf_ino[type]); return 0; } static inline __u64 cur_cp_crc(struct f2fs_checkpoint *cp) { size_t crc_offset = le32_to_cpu(cp->checksum_offset); return le32_to_cpu(*((__le32 *)((unsigned char *)cp + crc_offset))); } static inline bool __is_set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags = le32_to_cpu(cp->ckpt_flags); return ckpt_flags & f; } static inline bool is_set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { return __is_set_ckpt_flags(F2FS_CKPT(sbi), f); } static inline void __set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags |= f; cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __set_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void __clear_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags &= (~f); cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void clear_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void disable_nat_bits(struct f2fs_sb_info *sbi, bool lock) { unsigned long flags; /* * In order to re-enable nat_bits we need to call fsck.f2fs by * set_sbi_flag(sbi, SBI_NEED_FSCK). But it may give huge cost, * so let's rely on regular fsck or unclean shutdown. */ if (lock) spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), CP_NAT_BITS_FLAG); kvfree(NM_I(sbi)->nat_bits); NM_I(sbi)->nat_bits = NULL; if (lock) spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline bool enabled_nat_bits(struct f2fs_sb_info *sbi, struct cp_control *cpc) { bool set = is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG); return (cpc) ? (cpc->reason & CP_UMOUNT) && set : set; } static inline void f2fs_lock_op(struct f2fs_sb_info *sbi) { down_read(&sbi->cp_rwsem); } static inline int f2fs_trylock_op(struct f2fs_sb_info *sbi) { return down_read_trylock(&sbi->cp_rwsem); } static inline void f2fs_unlock_op(struct f2fs_sb_info *sbi) { up_read(&sbi->cp_rwsem); } static inline void f2fs_lock_all(struct f2fs_sb_info *sbi) { down_write(&sbi->cp_rwsem); } static inline void f2fs_unlock_all(struct f2fs_sb_info *sbi) { up_write(&sbi->cp_rwsem); } static inline int __get_cp_reason(struct f2fs_sb_info *sbi) { int reason = CP_SYNC; if (test_opt(sbi, FASTBOOT)) reason = CP_FASTBOOT; if (is_sbi_flag_set(sbi, SBI_IS_CLOSE)) reason = CP_UMOUNT; return reason; } static inline bool __remain_node_summaries(int reason) { return (reason & (CP_UMOUNT | CP_FASTBOOT)); } static inline bool __exist_node_summaries(struct f2fs_sb_info *sbi) { return (is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG) || is_set_ckpt_flags(sbi, CP_FASTBOOT_FLAG)); } /* * Check whether the inode has blocks or not */ static inline int F2FS_HAS_BLOCKS(struct inode *inode) { block_t xattr_block = F2FS_I(inode)->i_xattr_nid ? 1 : 0; return (inode->i_blocks >> F2FS_LOG_SECTORS_PER_BLOCK) > xattr_block; } static inline bool f2fs_has_xattr_block(unsigned int ofs) { return ofs == XATTR_NODE_OFFSET; } static inline bool __allow_reserved_blocks(struct f2fs_sb_info *sbi, struct inode *inode, bool cap) { if (!inode) return true; if (!test_opt(sbi, RESERVE_ROOT)) return false; if (IS_NOQUOTA(inode)) return true; if (uid_eq(F2FS_OPTION(sbi).s_resuid, current_fsuid())) return true; if (!gid_eq(F2FS_OPTION(sbi).s_resgid, GLOBAL_ROOT_GID) && in_group_p(F2FS_OPTION(sbi).s_resgid)) return true; if (cap && capable(CAP_SYS_RESOURCE)) return true; return false; } static inline void f2fs_i_blocks_write(struct inode *, block_t, bool, bool); static inline int inc_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, blkcnt_t *count) { blkcnt_t diff = 0, release = 0; block_t avail_user_block_count; int ret; ret = dquot_reserve_block(inode, *count); if (ret) return ret; if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); release = *count; goto enospc; } /* * let's increase this in prior to actual block count change in order * for f2fs_sync_file to avoid data races when deciding checkpoint. */ percpu_counter_add(&sbi->alloc_valid_block_count, (*count)); spin_lock(&sbi->stat_lock); sbi->total_valid_block_count += (block_t)(*count); avail_user_block_count = sbi->user_block_count - sbi->current_reserved_blocks; if (!__allow_reserved_blocks(sbi, inode, true)) avail_user_block_count -= F2FS_OPTION(sbi).root_reserved_blocks; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) { if (avail_user_block_count > sbi->unusable_block_count) avail_user_block_count -= sbi->unusable_block_count; else avail_user_block_count = 0; } if (unlikely(sbi->total_valid_block_count > avail_user_block_count)) { diff = sbi->total_valid_block_count - avail_user_block_count; if (diff > *count) diff = *count; *count -= diff; release = diff; sbi->total_valid_block_count -= diff; if (!*count) { spin_unlock(&sbi->stat_lock); goto enospc; } } spin_unlock(&sbi->stat_lock); if (unlikely(release)) { percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); } f2fs_i_blocks_write(inode, *count, true, true); return 0; enospc: percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); return -ENOSPC; } __printf(2, 3) void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...); #define f2fs_err(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_ERR fmt, ##__VA_ARGS__) #define f2fs_warn(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_WARNING fmt, ##__VA_ARGS__) #define f2fs_notice(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_NOTICE fmt, ##__VA_ARGS__) #define f2fs_info(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_INFO fmt, ##__VA_ARGS__) #define f2fs_debug(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_DEBUG fmt, ##__VA_ARGS__) static inline void dec_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, block_t count) { blkcnt_t sectors = count << F2FS_LOG_SECTORS_PER_BLOCK; spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, sbi->total_valid_block_count < (block_t) count); sbi->total_valid_block_count -= (block_t)count; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks = min(sbi->reserved_blocks, sbi->current_reserved_blocks + count); spin_unlock(&sbi->stat_lock); if (unlikely(inode->i_blocks < sectors)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu, sectors:%llu", inode->i_ino, (unsigned long long)inode->i_blocks, (unsigned long long)sectors); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, count, false, true); } static inline void inc_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_inc(&sbi->nr_pages[count_type]); if (count_type == F2FS_DIRTY_DENTS || count_type == F2FS_DIRTY_NODES || count_type == F2FS_DIRTY_META || count_type == F2FS_DIRTY_QDATA || count_type == F2FS_DIRTY_IMETA) set_sbi_flag(sbi, SBI_IS_DIRTY); } static inline void inode_inc_dirty_pages(struct inode *inode) { atomic_inc(&F2FS_I(inode)->dirty_pages); inc_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) inc_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline void dec_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_dec(&sbi->nr_pages[count_type]); } static inline void inode_dec_dirty_pages(struct inode *inode) { if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) && !S_ISLNK(inode->i_mode)) return; atomic_dec(&F2FS_I(inode)->dirty_pages); dec_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) dec_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline s64 get_pages(struct f2fs_sb_info *sbi, int count_type) { return atomic_read(&sbi->nr_pages[count_type]); } static inline int get_dirty_pages(struct inode *inode) { return atomic_read(&F2FS_I(inode)->dirty_pages); } static inline int get_blocktype_secs(struct f2fs_sb_info *sbi, int block_type) { unsigned int pages_per_sec = sbi->segs_per_sec * sbi->blocks_per_seg; unsigned int segs = (get_pages(sbi, block_type) + pages_per_sec - 1) >> sbi->log_blocks_per_seg; return segs / sbi->segs_per_sec; } static inline block_t valid_user_blocks(struct f2fs_sb_info *sbi) { return sbi->total_valid_block_count; } static inline block_t discard_blocks(struct f2fs_sb_info *sbi) { return sbi->discard_blks; } static inline unsigned long __bitmap_size(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); /* return NAT or SIT bitmap */ if (flag == NAT_BITMAP) return le32_to_cpu(ckpt->nat_ver_bitmap_bytesize); else if (flag == SIT_BITMAP) return le32_to_cpu(ckpt->sit_ver_bitmap_bytesize); return 0; } static inline block_t __cp_payload(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_payload); } static inline void *__bitmap_ptr(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); int offset; if (is_set_ckpt_flags(sbi, CP_LARGE_NAT_BITMAP_FLAG)) { offset = (flag == SIT_BITMAP) ? le32_to_cpu(ckpt->nat_ver_bitmap_bytesize) : 0; /* * if large_nat_bitmap feature is enabled, leave checksum * protection for all nat/sit bitmaps. */ return &ckpt->sit_nat_version_bitmap + offset + sizeof(__le32); } if (__cp_payload(sbi) > 0) { if (flag == NAT_BITMAP) return &ckpt->sit_nat_version_bitmap; else return (unsigned char *)ckpt + F2FS_BLKSIZE; } else { offset = (flag == NAT_BITMAP) ? le32_to_cpu(ckpt->sit_ver_bitmap_bytesize) : 0; return &ckpt->sit_nat_version_bitmap + offset; } } static inline block_t __start_cp_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 2) start_addr += sbi->blocks_per_seg; return start_addr; } static inline block_t __start_cp_next_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 1) start_addr += sbi->blocks_per_seg; return start_addr; } static inline void __set_cp_next_pack(struct f2fs_sb_info *sbi) { sbi->cur_cp_pack = (sbi->cur_cp_pack == 1) ? 2 : 1; } static inline block_t __start_sum_addr(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_CKPT(sbi)->cp_pack_start_sum); } static inline int inc_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { block_t valid_block_count; unsigned int valid_node_count, user_block_count; int err; if (is_inode) { if (inode) { err = dquot_alloc_inode(inode); if (err) return err; } } else { err = dquot_reserve_block(inode, 1); if (err) return err; } if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); goto enospc; } spin_lock(&sbi->stat_lock); valid_block_count = sbi->total_valid_block_count + sbi->current_reserved_blocks + 1; if (!__allow_reserved_blocks(sbi, inode, false)) valid_block_count += F2FS_OPTION(sbi).root_reserved_blocks; user_block_count = sbi->user_block_count; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) user_block_count -= sbi->unusable_block_count; if (unlikely(valid_block_count > user_block_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } valid_node_count = sbi->total_valid_node_count + 1; if (unlikely(valid_node_count > sbi->total_node_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } sbi->total_valid_node_count++; sbi->total_valid_block_count++; spin_unlock(&sbi->stat_lock); if (inode) { if (is_inode) f2fs_mark_inode_dirty_sync(inode, true); else f2fs_i_blocks_write(inode, 1, true, true); } percpu_counter_inc(&sbi->alloc_valid_block_count); return 0; enospc: if (is_inode) { if (inode) dquot_free_inode(inode); } else { dquot_release_reservation_block(inode, 1); } return -ENOSPC; } static inline void dec_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, !sbi->total_valid_block_count); f2fs_bug_on(sbi, !sbi->total_valid_node_count); sbi->total_valid_node_count--; sbi->total_valid_block_count--; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks++; spin_unlock(&sbi->stat_lock); if (is_inode) { dquot_free_inode(inode); } else { if (unlikely(inode->i_blocks == 0)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu", inode->i_ino, (unsigned long long)inode->i_blocks); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, 1, false, true); } } static inline unsigned int valid_node_count(struct f2fs_sb_info *sbi) { return sbi->total_valid_node_count; } static inline void inc_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_inc(&sbi->total_valid_inode_count); } static inline void dec_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_dec(&sbi->total_valid_inode_count); } static inline s64 valid_inode_count(struct f2fs_sb_info *sbi) { return percpu_counter_sum_positive(&sbi->total_valid_inode_count); } static inline struct page *f2fs_grab_cache_page(struct address_space *mapping, pgoff_t index, bool for_write) { struct page *page; if (IS_ENABLED(CONFIG_F2FS_FAULT_INJECTION)) { if (!for_write) page = find_get_page_flags(mapping, index, FGP_LOCK | FGP_ACCESSED); else page = find_lock_page(mapping, index); if (page) return page; if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_ALLOC)) { f2fs_show_injection_info(FAULT_PAGE_ALLOC); return NULL; } } if (!for_write) return grab_cache_page(mapping, index); return grab_cache_page_write_begin(mapping, index, AOP_FLAG_NOFS); } static inline struct page *f2fs_pagecache_get_page( struct address_space *mapping, pgoff_t index, int fgp_flags, gfp_t gfp_mask) { if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_GET)) { f2fs_show_injection_info(FAULT_PAGE_GET); return NULL; } return pagecache_get_page(mapping, index, fgp_flags, gfp_mask); } static inline void f2fs_copy_page(struct page *src, struct page *dst) { char *src_kaddr = kmap(src); char *dst_kaddr = kmap(dst); memcpy(dst_kaddr, src_kaddr, PAGE_SIZE); kunmap(dst); kunmap(src); } static inline void f2fs_put_page(struct page *page, int unlock) { if (!page) return; if (unlock) { f2fs_bug_on(F2FS_P_SB(page), !PageLocked(page)); unlock_page(page); } put_page(page); } static inline void f2fs_put_dnode(struct dnode_of_data *dn) { if (dn->node_page) f2fs_put_page(dn->node_page, 1); if (dn->inode_page && dn->node_page != dn->inode_page) f2fs_put_page(dn->inode_page, 0); dn->node_page = NULL; dn->inode_page = NULL; } static inline struct kmem_cache *f2fs_kmem_cache_create(const char *name, size_t size) { return kmem_cache_create(name, size, 0, SLAB_RECLAIM_ACCOUNT, NULL); } static inline void *f2fs_kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags) { void *entry; entry = kmem_cache_alloc(cachep, flags); if (!entry) entry = kmem_cache_alloc(cachep, flags | __GFP_NOFAIL); return entry; } static inline struct bio *f2fs_bio_alloc(struct f2fs_sb_info *sbi, int npages, bool no_fail) { struct bio *bio; if (no_fail) { /* No failure on bio allocation */ bio = bio_alloc(GFP_NOIO, npages); if (!bio) bio = bio_alloc(GFP_NOIO | __GFP_NOFAIL, npages); return bio; } if (time_to_inject(sbi, FAULT_ALLOC_BIO)) { f2fs_show_injection_info(FAULT_ALLOC_BIO); return NULL; } return bio_alloc(GFP_KERNEL, npages); } static inline bool is_idle(struct f2fs_sb_info *sbi, int type) { if (sbi->gc_mode == GC_URGENT) return true; if (get_pages(sbi, F2FS_RD_DATA) || get_pages(sbi, F2FS_RD_NODE) || get_pages(sbi, F2FS_RD_META) || get_pages(sbi, F2FS_WB_DATA) || get_pages(sbi, F2FS_WB_CP_DATA) || get_pages(sbi, F2FS_DIO_READ) || get_pages(sbi, F2FS_DIO_WRITE)) return false; if (type != DISCARD_TIME && SM_I(sbi) && SM_I(sbi)->dcc_info && atomic_read(&SM_I(sbi)->dcc_info->queued_discard)) return false; if (SM_I(sbi) && SM_I(sbi)->fcc_info && atomic_read(&SM_I(sbi)->fcc_info->queued_flush)) return false; return f2fs_time_over(sbi, type); } static inline void f2fs_radix_tree_insert(struct radix_tree_root *root, unsigned long index, void *item) { while (radix_tree_insert(root, index, item)) cond_resched(); } #define RAW_IS_INODE(p) ((p)->footer.nid == (p)->footer.ino) static inline bool IS_INODE(struct page *page) { struct f2fs_node *p = F2FS_NODE(page); return RAW_IS_INODE(p); } static inline int offset_in_addr(struct f2fs_inode *i) { return (i->i_inline & F2FS_EXTRA_ATTR) ? (le16_to_cpu(i->i_extra_isize) / sizeof(__le32)) : 0; } static inline __le32 *blkaddr_in_node(struct f2fs_node *node) { return RAW_IS_INODE(node) ? node->i.i_addr : node->dn.addr; } static inline int f2fs_has_extra_attr(struct inode *inode); static inline block_t datablock_addr(struct inode *inode, struct page *node_page, unsigned int offset) { struct f2fs_node *raw_node; __le32 *addr_array; int base = 0; bool is_inode = IS_INODE(node_page); raw_node = F2FS_NODE(node_page); /* from GC path only */ if (is_inode) { if (!inode) base = offset_in_addr(&raw_node->i); else if (f2fs_has_extra_attr(inode)) base = get_extra_isize(inode); } addr_array = blkaddr_in_node(raw_node); return le32_to_cpu(addr_array[base + offset]); } static inline int f2fs_test_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); return mask & *addr; } static inline void f2fs_set_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr |= mask; } static inline void f2fs_clear_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr &= ~mask; } static inline int f2fs_test_and_set_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr |= mask; return ret; } static inline int f2fs_test_and_clear_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr &= ~mask; return ret; } static inline void f2fs_change_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr ^= mask; } /* * On-disk inode flags (f2fs_inode::i_flags) */ #define F2FS_SYNC_FL 0x00000008 /* Synchronous updates */ #define F2FS_IMMUTABLE_FL 0x00000010 /* Immutable file */ #define F2FS_APPEND_FL 0x00000020 /* writes to file may only append */ #define F2FS_NODUMP_FL 0x00000040 /* do not dump file */ #define F2FS_NOATIME_FL 0x00000080 /* do not update atime */ #define F2FS_INDEX_FL 0x00001000 /* hash-indexed directory */ #define F2FS_DIRSYNC_FL 0x00010000 /* dirsync behaviour (directories only) */ #define F2FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */ /* Flags that should be inherited by new inodes from their parent. */ #define F2FS_FL_INHERITED (F2FS_SYNC_FL | F2FS_NODUMP_FL | F2FS_NOATIME_FL | \ F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL) /* Flags that are appropriate for regular files (all but dir-specific ones). */ #define F2FS_REG_FLMASK (~(F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL)) /* Flags that are appropriate for non-directories/regular files. */ #define F2FS_OTHER_FLMASK (F2FS_NODUMP_FL | F2FS_NOATIME_FL) static inline __u32 f2fs_mask_flags(umode_t mode, __u32 flags) { if (S_ISDIR(mode)) return flags; else if (S_ISREG(mode)) return flags & F2FS_REG_FLMASK; else return flags & F2FS_OTHER_FLMASK; } /* used for f2fs_inode_info->flags */ enum { FI_NEW_INODE, /* indicate newly allocated inode */ FI_DIRTY_INODE, /* indicate inode is dirty or not */ FI_AUTO_RECOVER, /* indicate inode is recoverable */ FI_DIRTY_DIR, /* indicate directory has dirty pages */ FI_INC_LINK, /* need to increment i_nlink */ FI_ACL_MODE, /* indicate acl mode */ FI_NO_ALLOC, /* should not allocate any blocks */ FI_FREE_NID, /* free allocated nide */ FI_NO_EXTENT, /* not to use the extent cache */ FI_INLINE_XATTR, /* used for inline xattr */ FI_INLINE_DATA, /* used for inline data*/ FI_INLINE_DENTRY, /* used for inline dentry */ FI_APPEND_WRITE, /* inode has appended data */ FI_UPDATE_WRITE, /* inode has in-place-update data */ FI_NEED_IPU, /* used for ipu per file */ FI_ATOMIC_FILE, /* indicate atomic file */ FI_ATOMIC_COMMIT, /* indicate the state of atomical committing */ FI_VOLATILE_FILE, /* indicate volatile file */ FI_FIRST_BLOCK_WRITTEN, /* indicate #0 data block was written */ FI_DROP_CACHE, /* drop dirty page cache */ FI_DATA_EXIST, /* indicate data exists */ FI_INLINE_DOTS, /* indicate inline dot dentries */ FI_DO_DEFRAG, /* indicate defragment is running */ FI_DIRTY_FILE, /* indicate regular/symlink has dirty pages */ FI_NO_PREALLOC, /* indicate skipped preallocated blocks */ FI_HOT_DATA, /* indicate file is hot */ FI_EXTRA_ATTR, /* indicate file has extra attribute */ FI_PROJ_INHERIT, /* indicate file inherits projectid */ FI_PIN_FILE, /* indicate file should not be gced */ FI_ATOMIC_REVOKE_REQUEST, /* request to drop atomic data */ }; static inline void __mark_inode_dirty_flag(struct inode *inode, int flag, bool set) { switch (flag) { case FI_INLINE_XATTR: case FI_INLINE_DATA: case FI_INLINE_DENTRY: case FI_NEW_INODE: if (set) return; /* fall through */ case FI_DATA_EXIST: case FI_INLINE_DOTS: case FI_PIN_FILE: f2fs_mark_inode_dirty_sync(inode, true); } } static inline void set_inode_flag(struct inode *inode, int flag) { if (!test_bit(flag, &F2FS_I(inode)->flags)) set_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, true); } static inline int is_inode_flag_set(struct inode *inode, int flag) { return test_bit(flag, &F2FS_I(inode)->flags); } static inline void clear_inode_flag(struct inode *inode, int flag) { if (test_bit(flag, &F2FS_I(inode)->flags)) clear_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, false); } static inline void set_acl_inode(struct inode *inode, umode_t mode) { F2FS_I(inode)->i_acl_mode = mode; set_inode_flag(inode, FI_ACL_MODE); f2fs_mark_inode_dirty_sync(inode, false); } static inline void f2fs_i_links_write(struct inode *inode, bool inc) { if (inc) inc_nlink(inode); else drop_nlink(inode); f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_blocks_write(struct inode *inode, block_t diff, bool add, bool claim) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); /* add = 1, claim = 1 should be dquot_reserve_block in pair */ if (add) { if (claim) dquot_claim_block(inode, diff); else dquot_alloc_block_nofail(inode, diff); } else { dquot_free_block(inode, diff); } f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_size_write(struct inode *inode, loff_t i_size) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); if (i_size_read(inode) == i_size) return; i_size_write(inode, i_size); f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_depth_write(struct inode *inode, unsigned int depth) { F2FS_I(inode)->i_current_depth = depth; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_gc_failures_write(struct inode *inode, unsigned int count) { F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN] = count; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_xnid_write(struct inode *inode, nid_t xnid) { F2FS_I(inode)->i_xattr_nid = xnid; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_pino_write(struct inode *inode, nid_t pino) { F2FS_I(inode)->i_pino = pino; f2fs_mark_inode_dirty_sync(inode, true); } static inline void get_inline_info(struct inode *inode, struct f2fs_inode *ri) { struct f2fs_inode_info *fi = F2FS_I(inode); if (ri->i_inline & F2FS_INLINE_XATTR) set_bit(FI_INLINE_XATTR, &fi->flags); if (ri->i_inline & F2FS_INLINE_DATA) set_bit(FI_INLINE_DATA, &fi->flags); if (ri->i_inline & F2FS_INLINE_DENTRY) set_bit(FI_INLINE_DENTRY, &fi->flags); if (ri->i_inline & F2FS_DATA_EXIST) set_bit(FI_DATA_EXIST, &fi->flags); if (ri->i_inline & F2FS_INLINE_DOTS) set_bit(FI_INLINE_DOTS, &fi->flags); if (ri->i_inline & F2FS_EXTRA_ATTR) set_bit(FI_EXTRA_ATTR, &fi->flags); if (ri->i_inline & F2FS_PIN_FILE) set_bit(FI_PIN_FILE, &fi->flags); } static inline void set_raw_inline(struct inode *inode, struct f2fs_inode *ri) { ri->i_inline = 0; if (is_inode_flag_set(inode, FI_INLINE_XATTR)) ri->i_inline |= F2FS_INLINE_XATTR; if (is_inode_flag_set(inode, FI_INLINE_DATA)) ri->i_inline |= F2FS_INLINE_DATA; if (is_inode_flag_set(inode, FI_INLINE_DENTRY)) ri->i_inline |= F2FS_INLINE_DENTRY; if (is_inode_flag_set(inode, FI_DATA_EXIST)) ri->i_inline |= F2FS_DATA_EXIST; if (is_inode_flag_set(inode, FI_INLINE_DOTS)) ri->i_inline |= F2FS_INLINE_DOTS; if (is_inode_flag_set(inode, FI_EXTRA_ATTR)) ri->i_inline |= F2FS_EXTRA_ATTR; if (is_inode_flag_set(inode, FI_PIN_FILE)) ri->i_inline |= F2FS_PIN_FILE; } static inline int f2fs_has_extra_attr(struct inode *inode) { return is_inode_flag_set(inode, FI_EXTRA_ATTR); } static inline int f2fs_has_inline_xattr(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_XATTR); } static inline unsigned int addrs_per_inode(struct inode *inode) { unsigned int addrs = CUR_ADDRS_PER_INODE(inode) - get_inline_xattr_addrs(inode); return ALIGN_DOWN(addrs, 1); } static inline unsigned int addrs_per_block(struct inode *inode) { return ALIGN_DOWN(DEF_ADDRS_PER_BLOCK, 1); } static inline void *inline_xattr_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); return (void *)&(ri->i_addr[DEF_ADDRS_PER_INODE - get_inline_xattr_addrs(inode)]); } static inline int inline_xattr_size(struct inode *inode) { if (f2fs_has_inline_xattr(inode)) return get_inline_xattr_addrs(inode) * sizeof(__le32); return 0; } static inline int f2fs_has_inline_data(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DATA); } static inline int f2fs_exist_data(struct inode *inode) { return is_inode_flag_set(inode, FI_DATA_EXIST); } static inline int f2fs_has_inline_dots(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DOTS); } static inline bool f2fs_is_pinned_file(struct inode *inode) { return is_inode_flag_set(inode, FI_PIN_FILE); } static inline bool f2fs_is_atomic_file(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_FILE); } static inline bool f2fs_is_commit_atomic_write(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_COMMIT); } static inline bool f2fs_is_volatile_file(struct inode *inode) { return is_inode_flag_set(inode, FI_VOLATILE_FILE); } static inline bool f2fs_is_first_block_written(struct inode *inode) { return is_inode_flag_set(inode, FI_FIRST_BLOCK_WRITTEN); } static inline bool f2fs_is_drop_cache(struct inode *inode) { return is_inode_flag_set(inode, FI_DROP_CACHE); } static inline void *inline_data_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); int extra_size = get_extra_isize(inode); return (void *)&(ri->i_addr[extra_size + DEF_INLINE_RESERVED_SIZE]); } static inline int f2fs_has_inline_dentry(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DENTRY); } static inline int is_file(struct inode *inode, int type) { return F2FS_I(inode)->i_advise & type; } static inline void set_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise |= type; f2fs_mark_inode_dirty_sync(inode, true); } static inline void clear_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise &= ~type; f2fs_mark_inode_dirty_sync(inode, true); } static inline bool f2fs_skip_inode_update(struct inode *inode, int dsync) { bool ret; if (dsync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); ret = list_empty(&F2FS_I(inode)->gdirty_list); spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } if (!is_inode_flag_set(inode, FI_AUTO_RECOVER) || file_keep_isize(inode) || i_size_read(inode) & ~PAGE_MASK) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time, &inode->i_atime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 1, &inode->i_ctime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 2, &inode->i_mtime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 3, &F2FS_I(inode)->i_crtime)) return false; down_read(&F2FS_I(inode)->i_sem); ret = F2FS_I(inode)->last_disk_size == i_size_read(inode); up_read(&F2FS_I(inode)->i_sem); return ret; } static inline bool f2fs_readonly(struct super_block *sb) { return sb_rdonly(sb); } static inline bool f2fs_cp_error(struct f2fs_sb_info *sbi) { return is_set_ckpt_flags(sbi, CP_ERROR_FLAG); } static inline bool is_dot_dotdot(const struct qstr *str) { if (str->len == 1 && str->name[0] == '.') return true; if (str->len == 2 && str->name[0] == '.' && str->name[1] == '.') return true; return false; } static inline bool f2fs_may_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (!test_opt(sbi, EXTENT_CACHE) || is_inode_flag_set(inode, FI_NO_EXTENT)) return false; /* * for recovered files during mount do not create extents * if shrinker is not registered. */ if (list_empty(&sbi->s_list)) return false; return S_ISREG(inode->i_mode); } static inline void *f2fs_kmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { void *ret; if (time_to_inject(sbi, FAULT_KMALLOC)) { f2fs_show_injection_info(FAULT_KMALLOC); return NULL; } ret = kmalloc(size, flags); if (ret) return ret; return kvmalloc(size, flags); } static inline void *f2fs_kzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kmalloc(sbi, size, flags | __GFP_ZERO); } static inline void *f2fs_kvmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { if (time_to_inject(sbi, FAULT_KVMALLOC)) { f2fs_show_injection_info(FAULT_KVMALLOC); return NULL; } return kvmalloc(size, flags); } static inline void *f2fs_kvzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kvmalloc(sbi, size, flags | __GFP_ZERO); } static inline int get_extra_isize(struct inode *inode) { return F2FS_I(inode)->i_extra_isize / sizeof(__le32); } static inline int get_inline_xattr_addrs(struct inode *inode) { return F2FS_I(inode)->i_inline_xattr_size; } #define f2fs_get_inode_mode(i) \ ((is_inode_flag_set(i, FI_ACL_MODE)) ? \ (F2FS_I(i)->i_acl_mode) : ((i)->i_mode)) #define F2FS_TOTAL_EXTRA_ATTR_SIZE \ (offsetof(struct f2fs_inode, i_extra_end) - \ offsetof(struct f2fs_inode, i_extra_isize)) \ #define F2FS_OLD_ATTRIBUTE_SIZE (offsetof(struct f2fs_inode, i_addr)) #define F2FS_FITS_IN_INODE(f2fs_inode, extra_isize, field) \ ((offsetof(typeof(*(f2fs_inode)), field) + \ sizeof((f2fs_inode)->field)) \ <= (F2FS_OLD_ATTRIBUTE_SIZE + (extra_isize))) \ static inline void f2fs_reset_iostat(struct f2fs_sb_info *sbi) { int i; spin_lock(&sbi->iostat_lock); for (i = 0; i < NR_IO_TYPE; i++) sbi->write_iostat[i] = 0; spin_unlock(&sbi->iostat_lock); } static inline void f2fs_update_iostat(struct f2fs_sb_info *sbi, enum iostat_type type, unsigned long long io_bytes) { if (!sbi->iostat_enable) return; spin_lock(&sbi->iostat_lock); sbi->write_iostat[type] += io_bytes; if (type == APP_WRITE_IO || type == APP_DIRECT_IO) sbi->write_iostat[APP_BUFFERED_IO] = sbi->write_iostat[APP_WRITE_IO] - sbi->write_iostat[APP_DIRECT_IO]; spin_unlock(&sbi->iostat_lock); } #define __is_large_section(sbi) ((sbi)->segs_per_sec > 1) #define __is_meta_io(fio) (PAGE_TYPE_OF_BIO((fio)->type) == META) bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); static inline void verify_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type) { if (!f2fs_is_valid_blkaddr(sbi, blkaddr, type)) { f2fs_err(sbi, "invalid blkaddr: %u, type: %d, run fsck to fix.", blkaddr, type); f2fs_bug_on(sbi, 1); } } static inline bool __is_valid_data_blkaddr(block_t blkaddr) { if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR) return false; return true; } static inline void f2fs_set_page_private(struct page *page, unsigned long data) { if (PagePrivate(page)) return; get_page(page); SetPagePrivate(page); set_page_private(page, data); } static inline void f2fs_clear_page_private(struct page *page) { if (!PagePrivate(page)) return; set_page_private(page, 0); ClearPagePrivate(page); f2fs_put_page(page, 0); } /* * file.c */ int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync); void f2fs_truncate_data_blocks(struct dnode_of_data *dn); int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock); int f2fs_truncate(struct inode *inode); int f2fs_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int flags); int f2fs_setattr(struct dentry *dentry, struct iattr *attr); int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end); void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count); int f2fs_precache_extents(struct inode *inode); long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid); int f2fs_pin_file_control(struct inode *inode, bool inc); /* * inode.c */ void f2fs_set_inode_flags(struct inode *inode); bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct page *page); void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct page *page); struct inode *f2fs_iget(struct super_block *sb, unsigned long ino); struct inode *f2fs_iget_retry(struct super_block *sb, unsigned long ino); int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_update_inode(struct inode *inode, struct page *node_page); void f2fs_update_inode_page(struct inode *inode); int f2fs_write_inode(struct inode *inode, struct writeback_control *wbc); void f2fs_evict_inode(struct inode *inode); void f2fs_handle_failed_inode(struct inode *inode); /* * namei.c */ int f2fs_update_extension_list(struct f2fs_sb_info *sbi, const char *name, bool hot, bool set); struct dentry *f2fs_get_parent(struct dentry *child); /* * dir.c */ unsigned char f2fs_get_de_type(struct f2fs_dir_entry *de); struct f2fs_dir_entry *f2fs_find_target_dentry(struct fscrypt_name *fname, f2fs_hash_t namehash, int *max_slots, struct f2fs_dentry_ptr *d); int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d, unsigned int start_pos, struct fscrypt_str *fstr); void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent, struct f2fs_dentry_ptr *d); struct page *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct page *dpage); void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode, unsigned int current_depth); int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots); void f2fs_drop_nlink(struct inode *dir, struct inode *inode); struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir, const struct qstr *child, struct page **res_page); struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p); ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr, struct page **page); void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de, struct page *page, struct inode *inode); void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d, const struct qstr *name, f2fs_hash_t name_hash, unsigned int bit_pos); int f2fs_add_regular_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); int f2fs_add_dentry(struct inode *dir, struct fscrypt_name *fname, struct inode *inode, nid_t ino, umode_t mode); int f2fs_do_add_link(struct inode *dir, const struct qstr *name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); int f2fs_do_tmpfile(struct inode *inode, struct inode *dir); bool f2fs_empty_dir(struct inode *dir); static inline int f2fs_add_link(struct dentry *dentry, struct inode *inode) { return f2fs_do_add_link(d_inode(dentry->d_parent), &dentry->d_name, inode, inode->i_ino, inode->i_mode); } /* * super.c */ int f2fs_inode_dirtied(struct inode *inode, bool sync); void f2fs_inode_synced(struct inode *inode); int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly); int f2fs_quota_sync(struct super_block *sb, int type); void f2fs_quota_off_umount(struct super_block *sb); int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover); int f2fs_sync_fs(struct super_block *sb, int sync); int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi); /* * hash.c */ f2fs_hash_t f2fs_dentry_hash(const struct qstr *name_info, struct fscrypt_name *fname); /* * node.c */ struct dnode_of_data; struct node_info; int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type); bool f2fs_in_warm_node_list(struct f2fs_sb_info *sbi, struct page *page); void f2fs_init_fsync_node_info(struct f2fs_sb_info *sbi); void f2fs_del_fsync_node_entry(struct f2fs_sb_info *sbi, struct page *page); void f2fs_reset_fsync_node_info(struct f2fs_sb_info *sbi); int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid, struct node_info *ni); pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs); int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode); int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from); int f2fs_truncate_xattr_node(struct inode *inode); int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi, unsigned int seq_id); int f2fs_remove_inode_page(struct inode *inode); struct page *f2fs_new_inode_page(struct inode *inode); struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs); void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid); struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid); struct page *f2fs_get_node_page_ra(struct page *parent, int start); int f2fs_move_node_page(struct page *node_page, int gc_type); int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode, struct writeback_control *wbc, bool atomic, unsigned int *seq_id); int f2fs_sync_node_pages(struct f2fs_sb_info *sbi, struct writeback_control *wbc, bool do_balance, enum iostat_type io_type); int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount); bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid); void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid); void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid); int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_recover_inline_xattr(struct inode *inode, struct page *page); int f2fs_recover_xattr_data(struct inode *inode, struct page *page); int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page); int f2fs_restore_node_summary(struct f2fs_sb_info *sbi, unsigned int segno, struct f2fs_summary_block *sum); int f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_node_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_node_manager_caches(void); void f2fs_destroy_node_manager_caches(void); /* * segment.c */ bool f2fs_need_SSR(struct f2fs_sb_info *sbi); void f2fs_register_inmem_page(struct inode *inode, struct page *page); void f2fs_drop_inmem_pages_all(struct f2fs_sb_info *sbi, bool gc_failure); void f2fs_drop_inmem_pages(struct inode *inode); void f2fs_drop_inmem_page(struct inode *inode, struct page *page); int f2fs_commit_inmem_pages(struct inode *inode); void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need); void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi); int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi); int f2fs_flush_device_cache(struct f2fs_sb_info *sbi); void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free); void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr); bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi); void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi); bool f2fs_issue_discard_timeout(struct f2fs_sb_info *sbi); void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi); block_t f2fs_get_unusable_blocks(struct f2fs_sb_info *sbi); int f2fs_disable_cp_again(struct f2fs_sb_info *sbi, block_t unusable); void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi); int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra); void allocate_segment_for_resize(struct f2fs_sb_info *sbi, int type, unsigned int start, unsigned int end); void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi); int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range); bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc); struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno); void f2fs_update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr); void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page, enum iostat_type io_type); void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio); void f2fs_outplace_write_data(struct dnode_of_data *dn, struct f2fs_io_info *fio); int f2fs_inplace_write_data(struct f2fs_io_info *fio); void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum, block_t old_blkaddr, block_t new_blkaddr, bool recover_curseg, bool recover_newaddr); void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn, block_t old_addr, block_t new_addr, unsigned char version, bool recover_curseg, bool recover_newaddr); void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page, block_t old_blkaddr, block_t *new_blkaddr, struct f2fs_summary *sum, int type, struct f2fs_io_info *fio, bool add_list); void f2fs_wait_on_page_writeback(struct page *page, enum page_type type, bool ordered, bool locked); void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr); void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr, block_t len); void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk); void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk); int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type, unsigned int val, int alloc); void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_segment_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_segment_manager_caches(void); void f2fs_destroy_segment_manager_caches(void); int f2fs_rw_hint_to_seg_type(enum rw_hint hint); enum rw_hint f2fs_io_type_to_rw_hint(struct f2fs_sb_info *sbi, enum page_type type, enum temp_type temp); /* * checkpoint.c */ void f2fs_stop_checkpoint(struct f2fs_sb_info *sbi, bool end_io); struct page *f2fs_grab_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page_nofail(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_tmp_page(struct f2fs_sb_info *sbi, pgoff_t index); bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); int f2fs_ra_meta_pages(struct f2fs_sb_info *sbi, block_t start, int nrpages, int type, bool sync); void f2fs_ra_meta_pages_cond(struct f2fs_sb_info *sbi, pgoff_t index); long f2fs_sync_meta_pages(struct f2fs_sb_info *sbi, enum page_type type, long nr_to_write, enum iostat_type io_type); void f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all); bool f2fs_exist_written_data(struct f2fs_sb_info *sbi, nid_t ino, int mode); void f2fs_set_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); bool f2fs_is_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); int f2fs_sync_inode_meta(struct f2fs_sb_info *sbi); int f2fs_acquire_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_release_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_add_orphan_inode(struct inode *inode); void f2fs_remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_recover_orphan_inodes(struct f2fs_sb_info *sbi); int f2fs_get_valid_checkpoint(struct f2fs_sb_info *sbi); void f2fs_update_dirty_page(struct inode *inode, struct page *page); void f2fs_remove_dirty_inode(struct inode *inode); int f2fs_sync_dirty_inodes(struct f2fs_sb_info *sbi, enum inode_type type); void f2fs_wait_on_all_pages_writeback(struct f2fs_sb_info *sbi); int f2fs_write_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_init_ino_entry_info(struct f2fs_sb_info *sbi); int __init f2fs_create_checkpoint_caches(void); void f2fs_destroy_checkpoint_caches(void); /* * data.c */ int f2fs_init_post_read_processing(void); void f2fs_destroy_post_read_processing(void); void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type); void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, nid_t ino, enum page_type type); void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi); int f2fs_submit_page_bio(struct f2fs_io_info *fio); int f2fs_merge_page_bio(struct f2fs_io_info *fio); void f2fs_submit_page_write(struct f2fs_io_info *fio); struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi, block_t blk_addr, struct bio *bio); int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_set_data_blkaddr(struct dnode_of_data *dn); void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr); int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count); int f2fs_reserve_new_block(struct dnode_of_data *dn); int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index); int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from); int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index); struct page *f2fs_get_read_data_page(struct inode *inode, pgoff_t index, int op_flags, bool for_write); struct page *f2fs_find_data_page(struct inode *inode, pgoff_t index); struct page *f2fs_get_lock_data_page(struct inode *inode, pgoff_t index, bool for_write); struct page *f2fs_get_new_data_page(struct inode *inode, struct page *ipage, pgoff_t index, bool new_i_size); int f2fs_do_write_data_page(struct f2fs_io_info *fio); void __do_map_lock(struct f2fs_sb_info *sbi, int flag, bool lock); int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int create, int flag); int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len); bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio); bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio); void f2fs_invalidate_page(struct page *page, unsigned int offset, unsigned int length); int f2fs_release_page(struct page *page, gfp_t wait); #ifdef CONFIG_MIGRATION int f2fs_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode); #endif bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len); void f2fs_clear_page_cache_dirty_tag(struct page *page); /* * gc.c */ int f2fs_start_gc_thread(struct f2fs_sb_info *sbi); void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi); block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode); int f2fs_gc(struct f2fs_sb_info *sbi, bool sync, bool background, unsigned int segno); void f2fs_build_gc_manager(struct f2fs_sb_info *sbi); int f2fs_resize_fs(struct f2fs_sb_info *sbi, __u64 block_count); /* * recovery.c */ int f2fs_recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only); bool f2fs_space_for_roll_forward(struct f2fs_sb_info *sbi); /* * debug.c */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info { struct list_head stat_list; struct f2fs_sb_info *sbi; int all_area_segs, sit_area_segs, nat_area_segs, ssa_area_segs; int main_area_segs, main_area_sections, main_area_zones; unsigned long long hit_largest, hit_cached, hit_rbtree; unsigned long long hit_total, total_ext; int ext_tree, zombie_tree, ext_node; int ndirty_node, ndirty_dent, ndirty_meta, ndirty_imeta; int ndirty_data, ndirty_qdata; int inmem_pages; unsigned int ndirty_dirs, ndirty_files, nquota_files, ndirty_all; int nats, dirty_nats, sits, dirty_sits; int free_nids, avail_nids, alloc_nids; int total_count, utilization; int bg_gc, nr_wb_cp_data, nr_wb_data; int nr_rd_data, nr_rd_node, nr_rd_meta; int nr_dio_read, nr_dio_write; unsigned int io_skip_bggc, other_skip_bggc; int nr_flushing, nr_flushed, flush_list_empty; int nr_discarding, nr_discarded; int nr_discard_cmd; unsigned int undiscard_blks; int inline_xattr, inline_inode, inline_dir, append, update, orphans; int aw_cnt, max_aw_cnt, vw_cnt, max_vw_cnt; unsigned int valid_count, valid_node_count, valid_inode_count, discard_blks; unsigned int bimodal, avg_vblocks; int util_free, util_valid, util_invalid; int rsvd_segs, overp_segs; int dirty_count, node_pages, meta_pages; int prefree_count, call_count, cp_count, bg_cp_count; int tot_segs, node_segs, data_segs, free_segs, free_secs; int bg_node_segs, bg_data_segs; int tot_blks, data_blks, node_blks; int bg_data_blks, bg_node_blks; unsigned long long skipped_atomic_files[2]; int curseg[NR_CURSEG_TYPE]; int cursec[NR_CURSEG_TYPE]; int curzone[NR_CURSEG_TYPE]; unsigned int meta_count[META_MAX]; unsigned int segment_count[2]; unsigned int block_count[2]; unsigned int inplace_count; unsigned long long base_mem, cache_mem, page_mem; }; static inline struct f2fs_stat_info *F2FS_STAT(struct f2fs_sb_info *sbi) { return (struct f2fs_stat_info *)sbi->stat_info; } #define stat_inc_cp_count(si) ((si)->cp_count++) #define stat_inc_bg_cp_count(si) ((si)->bg_cp_count++) #define stat_inc_call_count(si) ((si)->call_count++) #define stat_inc_bggc_count(sbi) ((sbi)->bg_gc++) #define stat_io_skip_bggc_count(sbi) ((sbi)->io_skip_bggc++) #define stat_other_skip_bggc_count(sbi) ((sbi)->other_skip_bggc++) #define stat_inc_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]++) #define stat_dec_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]--) #define stat_inc_total_hit(sbi) (atomic64_inc(&(sbi)->total_hit_ext)) #define stat_inc_rbtree_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_rbtree)) #define stat_inc_largest_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_largest)) #define stat_inc_cached_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_cached)) #define stat_inc_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_dec_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_inc_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_dec_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_inc_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_dec_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_inc_meta_count(sbi, blkaddr) \ do { \ if (blkaddr < SIT_I(sbi)->sit_base_addr) \ atomic_inc(&(sbi)->meta_count[META_CP]); \ else if (blkaddr < NM_I(sbi)->nat_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SIT]); \ else if (blkaddr < SM_I(sbi)->ssa_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_NAT]); \ else if (blkaddr < SM_I(sbi)->main_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SSA]); \ } while (0) #define stat_inc_seg_type(sbi, curseg) \ ((sbi)->segment_count[(curseg)->alloc_type]++) #define stat_inc_block_count(sbi, curseg) \ ((sbi)->block_count[(curseg)->alloc_type]++) #define stat_inc_inplace_blocks(sbi) \ (atomic_inc(&(sbi)->inplace_count)) #define stat_inc_atomic_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->aw_cnt)) #define stat_dec_atomic_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->aw_cnt)) #define stat_update_max_atomic_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->aw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_aw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_aw_cnt, cur); \ } while (0) #define stat_inc_volatile_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->vw_cnt)) #define stat_dec_volatile_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->vw_cnt)) #define stat_update_max_volatile_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->vw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_vw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_vw_cnt, cur); \ } while (0) #define stat_inc_seg_count(sbi, type, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ si->tot_segs++; \ if ((type) == SUM_TYPE_DATA) { \ si->data_segs++; \ si->bg_data_segs += (gc_type == BG_GC) ? 1 : 0; \ } else { \ si->node_segs++; \ si->bg_node_segs += (gc_type == BG_GC) ? 1 : 0; \ } \ } while (0) #define stat_inc_tot_blk_count(si, blks) \ ((si)->tot_blks += (blks)) #define stat_inc_data_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->data_blks += (blks); \ si->bg_data_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->node_blks += (blks); \ si->bg_node_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) int f2fs_build_stats(struct f2fs_sb_info *sbi); void f2fs_destroy_stats(struct f2fs_sb_info *sbi); void __init f2fs_create_root_stats(void); void f2fs_destroy_root_stats(void); #else #define stat_inc_cp_count(si) do { } while (0) #define stat_inc_bg_cp_count(si) do { } while (0) #define stat_inc_call_count(si) do { } while (0) #define stat_inc_bggc_count(si) do { } while (0) #define stat_io_skip_bggc_count(sbi) do { } while (0) #define stat_other_skip_bggc_count(sbi) do { } while (0) #define stat_inc_dirty_inode(sbi, type) do { } while (0) #define stat_dec_dirty_inode(sbi, type) do { } while (0) #define stat_inc_total_hit(sb) do { } while (0) #define stat_inc_rbtree_node_hit(sb) do { } while (0) #define stat_inc_largest_node_hit(sbi) do { } while (0) #define stat_inc_cached_node_hit(sbi) do { } while (0) #define stat_inc_inline_xattr(inode) do { } while (0) #define stat_dec_inline_xattr(inode) do { } while (0) #define stat_inc_inline_inode(inode) do { } while (0) #define stat_dec_inline_inode(inode) do { } while (0) #define stat_inc_inline_dir(inode) do { } while (0) #define stat_dec_inline_dir(inode) do { } while (0) #define stat_inc_atomic_write(inode) do { } while (0) #define stat_dec_atomic_write(inode) do { } while (0) #define stat_update_max_atomic_write(inode) do { } while (0) #define stat_inc_volatile_write(inode) do { } while (0) #define stat_dec_volatile_write(inode) do { } while (0) #define stat_update_max_volatile_write(inode) do { } while (0) #define stat_inc_meta_count(sbi, blkaddr) do { } while (0) #define stat_inc_seg_type(sbi, curseg) do { } while (0) #define stat_inc_block_count(sbi, curseg) do { } while (0) #define stat_inc_inplace_blocks(sbi) do { } while (0) #define stat_inc_seg_count(sbi, type, gc_type) do { } while (0) #define stat_inc_tot_blk_count(si, blks) do { } while (0) #define stat_inc_data_blk_count(sbi, blks, gc_type) do { } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) do { } while (0) static inline int f2fs_build_stats(struct f2fs_sb_info *sbi) { return 0; } static inline void f2fs_destroy_stats(struct f2fs_sb_info *sbi) { } static inline void __init f2fs_create_root_stats(void) { } static inline void f2fs_destroy_root_stats(void) { } #endif extern const struct file_operations f2fs_dir_operations; extern const struct file_operations f2fs_file_operations; extern const struct inode_operations f2fs_file_inode_operations; extern const struct address_space_operations f2fs_dblock_aops; extern const struct address_space_operations f2fs_node_aops; extern const struct address_space_operations f2fs_meta_aops; extern const struct inode_operations f2fs_dir_inode_operations; extern const struct inode_operations f2fs_symlink_inode_operations; extern const struct inode_operations f2fs_encrypted_symlink_inode_operations; extern const struct inode_operations f2fs_special_inode_operations; extern struct kmem_cache *f2fs_inode_entry_slab; /* * inline.c */ bool f2fs_may_inline_data(struct inode *inode); bool f2fs_may_inline_dentry(struct inode *inode); void f2fs_do_read_inline_data(struct page *page, struct page *ipage); void f2fs_truncate_inline_inode(struct inode *inode, struct page *ipage, u64 from); int f2fs_read_inline_data(struct inode *inode, struct page *page); int f2fs_convert_inline_page(struct dnode_of_data *dn, struct page *page); int f2fs_convert_inline_inode(struct inode *inode); int f2fs_write_inline_data(struct inode *inode, struct page *page); bool f2fs_recover_inline_data(struct inode *inode, struct page *npage); struct f2fs_dir_entry *f2fs_find_in_inline_dir(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); int f2fs_make_empty_inline_dir(struct inode *inode, struct inode *parent, struct page *ipage); int f2fs_add_inline_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_inline_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); bool f2fs_empty_inline_dir(struct inode *dir); int f2fs_read_inline_dir(struct file *file, struct dir_context *ctx, struct fscrypt_str *fstr); int f2fs_inline_data_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len); /* * shrinker.c */ unsigned long f2fs_shrink_count(struct shrinker *shrink, struct shrink_control *sc); unsigned long f2fs_shrink_scan(struct shrinker *shrink, struct shrink_control *sc); void f2fs_join_shrinker(struct f2fs_sb_info *sbi); void f2fs_leave_shrinker(struct f2fs_sb_info *sbi); /* * extent_cache.c */ struct rb_entry *f2fs_lookup_rb_tree(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs); struct rb_node **f2fs_lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi, struct rb_root_cached *root, struct rb_node **parent, unsigned int ofs, bool *leftmost); struct rb_entry *f2fs_lookup_rb_tree_ret(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs, struct rb_entry **prev_entry, struct rb_entry **next_entry, struct rb_node ***insert_p, struct rb_node **insert_parent, bool force, bool *leftmost); bool f2fs_check_rb_tree_consistence(struct f2fs_sb_info *sbi, struct rb_root_cached *root); unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink); bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext); void f2fs_drop_extent_tree(struct inode *inode); unsigned int f2fs_destroy_extent_node(struct inode *inode); void f2fs_destroy_extent_tree(struct inode *inode); bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs, struct extent_info *ei); void f2fs_update_extent_cache(struct dnode_of_data *dn); void f2fs_update_extent_cache_range(struct dnode_of_data *dn, pgoff_t fofs, block_t blkaddr, unsigned int len); void f2fs_init_extent_cache_info(struct f2fs_sb_info *sbi); int __init f2fs_create_extent_cache(void); void f2fs_destroy_extent_cache(void); /* * sysfs.c */ int __init f2fs_init_sysfs(void); void f2fs_exit_sysfs(void); int f2fs_register_sysfs(struct f2fs_sb_info *sbi); void f2fs_unregister_sysfs(struct f2fs_sb_info *sbi); /* * crypto support */ static inline bool f2fs_encrypted_file(struct inode *inode) { return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode); } static inline void f2fs_set_encrypted_inode(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION file_set_encrypt(inode); f2fs_set_inode_flags(inode); #endif } /* * Returns true if the reads of the inode's data need to undergo some * postprocessing step, like decryption or authenticity verification. */ static inline bool f2fs_post_read_required(struct inode *inode) { return f2fs_encrypted_file(inode); } #define F2FS_FEATURE_FUNCS(name, flagname) \ static inline int f2fs_sb_has_##name(struct f2fs_sb_info *sbi) \ { \ return F2FS_HAS_FEATURE(sbi, F2FS_FEATURE_##flagname); \ } F2FS_FEATURE_FUNCS(encrypt, ENCRYPT); F2FS_FEATURE_FUNCS(blkzoned, BLKZONED); F2FS_FEATURE_FUNCS(extra_attr, EXTRA_ATTR); F2FS_FEATURE_FUNCS(project_quota, PRJQUOTA); F2FS_FEATURE_FUNCS(inode_chksum, INODE_CHKSUM); F2FS_FEATURE_FUNCS(flexible_inline_xattr, FLEXIBLE_INLINE_XATTR); F2FS_FEATURE_FUNCS(quota_ino, QUOTA_INO); F2FS_FEATURE_FUNCS(inode_crtime, INODE_CRTIME); F2FS_FEATURE_FUNCS(lost_found, LOST_FOUND); F2FS_FEATURE_FUNCS(sb_chksum, SB_CHKSUM); #ifdef CONFIG_BLK_DEV_ZONED static inline bool f2fs_blkz_is_seq(struct f2fs_sb_info *sbi, int devi, block_t blkaddr) { unsigned int zno = blkaddr >> sbi->log_blocks_per_blkz; return test_bit(zno, FDEV(devi).blkz_seq); } #endif static inline bool f2fs_hw_should_discard(struct f2fs_sb_info *sbi) { return f2fs_sb_has_blkzoned(sbi); } static inline bool f2fs_bdev_support_discard(struct block_device *bdev) { return blk_queue_discard(bdev_get_queue(bdev)) || bdev_is_zoned(bdev); } static inline bool f2fs_hw_support_discard(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return f2fs_bdev_support_discard(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (f2fs_bdev_support_discard(FDEV(i).bdev)) return true; return false; } static inline bool f2fs_realtime_discard_enable(struct f2fs_sb_info *sbi) { return (test_opt(sbi, DISCARD) && f2fs_hw_support_discard(sbi)) || f2fs_hw_should_discard(sbi); } static inline bool f2fs_hw_is_readonly(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return bdev_read_only(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (bdev_read_only(FDEV(i).bdev)) return true; return false; } static inline void set_opt_mode(struct f2fs_sb_info *sbi, unsigned int mt) { clear_opt(sbi, ADAPTIVE); clear_opt(sbi, LFS); switch (mt) { case F2FS_MOUNT_ADAPTIVE: set_opt(sbi, ADAPTIVE); break; case F2FS_MOUNT_LFS: set_opt(sbi, LFS); break; } } static inline bool f2fs_may_encrypt(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION umode_t mode = inode->i_mode; return (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)); #else return false; #endif } static inline int block_unaligned_IO(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { unsigned int i_blkbits = READ_ONCE(inode->i_blkbits); unsigned int blocksize_mask = (1 << i_blkbits) - 1; loff_t offset = iocb->ki_pos; unsigned long align = offset | iov_iter_alignment(iter); return align & blocksize_mask; } static inline int allow_outplace_dio(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); return (test_opt(sbi, LFS) && (rw == WRITE) && !block_unaligned_IO(inode, iocb, iter)); } static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED)) return true; return false; } #ifdef CONFIG_F2FS_FAULT_INJECTION extern void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate, unsigned int type); #else #define f2fs_build_fault_attr(sbi, rate, type) do { } while (0) #endif static inline bool is_journalled_quota(struct f2fs_sb_info *sbi) { #ifdef CONFIG_QUOTA if (f2fs_sb_has_quota_ino(sbi)) return true; if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] || F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] || F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) return true; #endif return false; } #define EFSBADCRC EBADMSG /* Bad CRC detected */ #define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */ #endif /* _LINUX_F2FS_H */
// SPDX-License-Identifier: GPL-2.0 /* * fs/f2fs/f2fs.h * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ */ #ifndef _LINUX_F2FS_H #define _LINUX_F2FS_H #include <linux/uio.h> #include <linux/types.h> #include <linux/page-flags.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/crc32.h> #include <linux/magic.h> #include <linux/kobject.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/vmalloc.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/quotaops.h> #include <crypto/hash.h> #include <linux/fscrypt.h> #ifdef CONFIG_F2FS_CHECK_FS #define f2fs_bug_on(sbi, condition) BUG_ON(condition) #else #define f2fs_bug_on(sbi, condition) \ do { \ if (unlikely(condition)) { \ WARN_ON(1); \ set_sbi_flag(sbi, SBI_NEED_FSCK); \ } \ } while (0) #endif enum { FAULT_KMALLOC, FAULT_KVMALLOC, FAULT_PAGE_ALLOC, FAULT_PAGE_GET, FAULT_ALLOC_BIO, FAULT_ALLOC_NID, FAULT_ORPHAN, FAULT_BLOCK, FAULT_DIR_DEPTH, FAULT_EVICT_INODE, FAULT_TRUNCATE, FAULT_READ_IO, FAULT_CHECKPOINT, FAULT_DISCARD, FAULT_WRITE_IO, FAULT_MAX, }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define F2FS_ALL_FAULT_TYPE ((1 << FAULT_MAX) - 1) struct f2fs_fault_info { atomic_t inject_ops; unsigned int inject_rate; unsigned int inject_type; }; extern const char *f2fs_fault_name[FAULT_MAX]; #define IS_FAULT_SET(fi, type) ((fi)->inject_type & (1 << (type))) #endif /* * For mount options */ #define F2FS_MOUNT_BG_GC 0x00000001 #define F2FS_MOUNT_DISABLE_ROLL_FORWARD 0x00000002 #define F2FS_MOUNT_DISCARD 0x00000004 #define F2FS_MOUNT_NOHEAP 0x00000008 #define F2FS_MOUNT_XATTR_USER 0x00000010 #define F2FS_MOUNT_POSIX_ACL 0x00000020 #define F2FS_MOUNT_DISABLE_EXT_IDENTIFY 0x00000040 #define F2FS_MOUNT_INLINE_XATTR 0x00000080 #define F2FS_MOUNT_INLINE_DATA 0x00000100 #define F2FS_MOUNT_INLINE_DENTRY 0x00000200 #define F2FS_MOUNT_FLUSH_MERGE 0x00000400 #define F2FS_MOUNT_NOBARRIER 0x00000800 #define F2FS_MOUNT_FASTBOOT 0x00001000 #define F2FS_MOUNT_EXTENT_CACHE 0x00002000 #define F2FS_MOUNT_FORCE_FG_GC 0x00004000 #define F2FS_MOUNT_DATA_FLUSH 0x00008000 #define F2FS_MOUNT_FAULT_INJECTION 0x00010000 #define F2FS_MOUNT_ADAPTIVE 0x00020000 #define F2FS_MOUNT_LFS 0x00040000 #define F2FS_MOUNT_USRQUOTA 0x00080000 #define F2FS_MOUNT_GRPQUOTA 0x00100000 #define F2FS_MOUNT_PRJQUOTA 0x00200000 #define F2FS_MOUNT_QUOTA 0x00400000 #define F2FS_MOUNT_INLINE_XATTR_SIZE 0x00800000 #define F2FS_MOUNT_RESERVE_ROOT 0x01000000 #define F2FS_MOUNT_DISABLE_CHECKPOINT 0x02000000 #define F2FS_OPTION(sbi) ((sbi)->mount_opt) #define clear_opt(sbi, option) (F2FS_OPTION(sbi).opt &= ~F2FS_MOUNT_##option) #define set_opt(sbi, option) (F2FS_OPTION(sbi).opt |= F2FS_MOUNT_##option) #define test_opt(sbi, option) (F2FS_OPTION(sbi).opt & F2FS_MOUNT_##option) #define ver_after(a, b) (typecheck(unsigned long long, a) && \ typecheck(unsigned long long, b) && \ ((long long)((a) - (b)) > 0)) typedef u32 block_t; /* * should not change u32, since it is the on-disk block * address format, __le32. */ typedef u32 nid_t; struct f2fs_mount_info { unsigned int opt; int write_io_size_bits; /* Write IO size bits */ block_t root_reserved_blocks; /* root reserved blocks */ kuid_t s_resuid; /* reserved blocks for uid */ kgid_t s_resgid; /* reserved blocks for gid */ int active_logs; /* # of active logs */ int inline_xattr_size; /* inline xattr size */ #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info fault_info; /* For fault injection */ #endif #ifdef CONFIG_QUOTA /* Names of quota files with journalled quota */ char *s_qf_names[MAXQUOTAS]; int s_jquota_fmt; /* Format of quota to use */ #endif /* For which write hints are passed down to block layer */ int whint_mode; int alloc_mode; /* segment allocation policy */ int fsync_mode; /* fsync policy */ bool test_dummy_encryption; /* test dummy encryption */ block_t unusable_cap; /* Amount of space allowed to be * unusable when disabling checkpoint */ }; #define F2FS_FEATURE_ENCRYPT 0x0001 #define F2FS_FEATURE_BLKZONED 0x0002 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004 #define F2FS_FEATURE_EXTRA_ATTR 0x0008 #define F2FS_FEATURE_PRJQUOTA 0x0010 #define F2FS_FEATURE_INODE_CHKSUM 0x0020 #define F2FS_FEATURE_FLEXIBLE_INLINE_XATTR 0x0040 #define F2FS_FEATURE_QUOTA_INO 0x0080 #define F2FS_FEATURE_INODE_CRTIME 0x0100 #define F2FS_FEATURE_LOST_FOUND 0x0200 #define F2FS_FEATURE_VERITY 0x0400 /* reserved */ #define F2FS_FEATURE_SB_CHKSUM 0x0800 #define __F2FS_HAS_FEATURE(raw_super, mask) \ ((raw_super->feature & cpu_to_le32(mask)) != 0) #define F2FS_HAS_FEATURE(sbi, mask) __F2FS_HAS_FEATURE(sbi->raw_super, mask) #define F2FS_SET_FEATURE(sbi, mask) \ (sbi->raw_super->feature |= cpu_to_le32(mask)) #define F2FS_CLEAR_FEATURE(sbi, mask) \ (sbi->raw_super->feature &= ~cpu_to_le32(mask)) /* * Default values for user and/or group using reserved blocks */ #define F2FS_DEF_RESUID 0 #define F2FS_DEF_RESGID 0 /* * For checkpoint manager */ enum { NAT_BITMAP, SIT_BITMAP }; #define CP_UMOUNT 0x00000001 #define CP_FASTBOOT 0x00000002 #define CP_SYNC 0x00000004 #define CP_RECOVERY 0x00000008 #define CP_DISCARD 0x00000010 #define CP_TRIMMED 0x00000020 #define CP_PAUSE 0x00000040 #define MAX_DISCARD_BLOCKS(sbi) BLKS_PER_SEC(sbi) #define DEF_MAX_DISCARD_REQUEST 8 /* issue 8 discards per round */ #define DEF_MIN_DISCARD_ISSUE_TIME 50 /* 50 ms, if exists */ #define DEF_MID_DISCARD_ISSUE_TIME 500 /* 500 ms, if device busy */ #define DEF_MAX_DISCARD_ISSUE_TIME 60000 /* 60 s, if no candidates */ #define DEF_DISCARD_URGENT_UTIL 80 /* do more discard over 80% */ #define DEF_CP_INTERVAL 60 /* 60 secs */ #define DEF_IDLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_QUICK_INTERVAL 1 /* 1 secs */ #define DEF_UMOUNT_DISCARD_TIMEOUT 5 /* 5 secs */ struct cp_control { int reason; __u64 trim_start; __u64 trim_end; __u64 trim_minlen; }; /* * indicate meta/data type */ enum { META_CP, META_NAT, META_SIT, META_SSA, META_MAX, META_POR, DATA_GENERIC, /* check range only */ DATA_GENERIC_ENHANCE, /* strong check on range and segment bitmap */ DATA_GENERIC_ENHANCE_READ, /* * strong check on range and segment * bitmap but no warning due to race * condition of read on truncated area * by extent_cache */ META_GENERIC, }; /* for the list of ino */ enum { ORPHAN_INO, /* for orphan ino list */ APPEND_INO, /* for append ino list */ UPDATE_INO, /* for update ino list */ TRANS_DIR_INO, /* for trasactions dir ino list */ FLUSH_INO, /* for multiple device flushing */ MAX_INO_ENTRY, /* max. list */ }; struct ino_entry { struct list_head list; /* list head */ nid_t ino; /* inode number */ unsigned int dirty_device; /* dirty device bitmap */ }; /* for the list of inodes to be GCed */ struct inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ }; struct fsync_node_entry { struct list_head list; /* list head */ struct page *page; /* warm node page pointer */ unsigned int seq_id; /* sequence id */ }; /* for the bitmap indicate blocks to be discarded */ struct discard_entry { struct list_head list; /* list head */ block_t start_blkaddr; /* start blockaddr of current segment */ unsigned char discard_map[SIT_VBLOCK_MAP_SIZE]; /* segment discard bitmap */ }; /* default discard granularity of inner discard thread, unit: block count */ #define DEFAULT_DISCARD_GRANULARITY 16 /* max discard pend list number */ #define MAX_PLIST_NUM 512 #define plist_idx(blk_num) ((blk_num) >= MAX_PLIST_NUM ? \ (MAX_PLIST_NUM - 1) : ((blk_num) - 1)) enum { D_PREP, /* initial */ D_PARTIAL, /* partially submitted */ D_SUBMIT, /* all submitted */ D_DONE, /* finished */ }; struct discard_info { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_cmd { struct rb_node rb_node; /* rb node located in rb-tree */ union { struct { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_info di; /* discard info */ }; struct list_head list; /* command list */ struct completion wait; /* compleation */ struct block_device *bdev; /* bdev */ unsigned short ref; /* reference count */ unsigned char state; /* state */ unsigned char queued; /* queued discard */ int error; /* bio error */ spinlock_t lock; /* for state/bio_ref updating */ unsigned short bio_ref; /* bio reference count */ }; enum { DPOLICY_BG, DPOLICY_FORCE, DPOLICY_FSTRIM, DPOLICY_UMOUNT, MAX_DPOLICY, }; struct discard_policy { int type; /* type of discard */ unsigned int min_interval; /* used for candidates exist */ unsigned int mid_interval; /* used for device busy */ unsigned int max_interval; /* used for candidates not exist */ unsigned int max_requests; /* # of discards issued per round */ unsigned int io_aware_gran; /* minimum granularity discard not be aware of I/O */ bool io_aware; /* issue discard in idle time */ bool sync; /* submit discard with REQ_SYNC flag */ bool ordered; /* issue discard by lba order */ unsigned int granularity; /* discard granularity */ int timeout; /* discard timeout for put_super */ }; struct discard_cmd_control { struct task_struct *f2fs_issue_discard; /* discard thread */ struct list_head entry_list; /* 4KB discard entry list */ struct list_head pend_list[MAX_PLIST_NUM];/* store pending entries */ struct list_head wait_list; /* store on-flushing entries */ struct list_head fstrim_list; /* in-flight discard from fstrim */ wait_queue_head_t discard_wait_queue; /* waiting queue for wake-up */ unsigned int discard_wake; /* to wake up discard thread */ struct mutex cmd_lock; unsigned int nr_discards; /* # of discards in the list */ unsigned int max_discards; /* max. discards to be issued */ unsigned int discard_granularity; /* discard granularity */ unsigned int undiscard_blks; /* # of undiscard blocks */ unsigned int next_pos; /* next discard position */ atomic_t issued_discard; /* # of issued discard */ atomic_t queued_discard; /* # of queued discard */ atomic_t discard_cmd_cnt; /* # of cached cmd count */ struct rb_root_cached root; /* root of discard rb-tree */ bool rbtree_check; /* config for consistence check */ }; /* for the list of fsync inodes, used only during recovery */ struct fsync_inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ block_t blkaddr; /* block address locating the last fsync */ block_t last_dentry; /* block address locating the last dentry */ }; #define nats_in_cursum(jnl) (le16_to_cpu((jnl)->n_nats)) #define sits_in_cursum(jnl) (le16_to_cpu((jnl)->n_sits)) #define nat_in_journal(jnl, i) ((jnl)->nat_j.entries[i].ne) #define nid_in_journal(jnl, i) ((jnl)->nat_j.entries[i].nid) #define sit_in_journal(jnl, i) ((jnl)->sit_j.entries[i].se) #define segno_in_journal(jnl, i) ((jnl)->sit_j.entries[i].segno) #define MAX_NAT_JENTRIES(jnl) (NAT_JOURNAL_ENTRIES - nats_in_cursum(jnl)) #define MAX_SIT_JENTRIES(jnl) (SIT_JOURNAL_ENTRIES - sits_in_cursum(jnl)) static inline int update_nats_in_cursum(struct f2fs_journal *journal, int i) { int before = nats_in_cursum(journal); journal->n_nats = cpu_to_le16(before + i); return before; } static inline int update_sits_in_cursum(struct f2fs_journal *journal, int i) { int before = sits_in_cursum(journal); journal->n_sits = cpu_to_le16(before + i); return before; } static inline bool __has_cursum_space(struct f2fs_journal *journal, int size, int type) { if (type == NAT_JOURNAL) return size <= MAX_NAT_JENTRIES(journal); return size <= MAX_SIT_JENTRIES(journal); } /* * ioctl commands */ #define F2FS_IOC_GETFLAGS FS_IOC_GETFLAGS #define F2FS_IOC_SETFLAGS FS_IOC_SETFLAGS #define F2FS_IOC_GETVERSION FS_IOC_GETVERSION #define F2FS_IOCTL_MAGIC 0xf5 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) #define F2FS_IOC_RELEASE_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 4) #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) #define F2FS_IOC_GARBAGE_COLLECT _IOW(F2FS_IOCTL_MAGIC, 6, __u32) #define F2FS_IOC_WRITE_CHECKPOINT _IO(F2FS_IOCTL_MAGIC, 7) #define F2FS_IOC_DEFRAGMENT _IOWR(F2FS_IOCTL_MAGIC, 8, \ struct f2fs_defragment) #define F2FS_IOC_MOVE_RANGE _IOWR(F2FS_IOCTL_MAGIC, 9, \ struct f2fs_move_range) #define F2FS_IOC_FLUSH_DEVICE _IOW(F2FS_IOCTL_MAGIC, 10, \ struct f2fs_flush_device) #define F2FS_IOC_GARBAGE_COLLECT_RANGE _IOW(F2FS_IOCTL_MAGIC, 11, \ struct f2fs_gc_range) #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, __u32) #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) #define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) #define F2FS_IOC_PRECACHE_EXTENTS _IO(F2FS_IOCTL_MAGIC, 15) #define F2FS_IOC_RESIZE_FS _IOW(F2FS_IOCTL_MAGIC, 16, __u64) #define F2FS_IOC_SET_ENCRYPTION_POLICY FS_IOC_SET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_POLICY FS_IOC_GET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_PWSALT FS_IOC_GET_ENCRYPTION_PWSALT /* * should be same as XFS_IOC_GOINGDOWN. * Flags for going down operation used by FS_IOC_GOINGDOWN */ #define F2FS_IOC_SHUTDOWN _IOR('X', 125, __u32) /* Shutdown */ #define F2FS_GOING_DOWN_FULLSYNC 0x0 /* going down with full sync */ #define F2FS_GOING_DOWN_METASYNC 0x1 /* going down with metadata */ #define F2FS_GOING_DOWN_NOSYNC 0x2 /* going down */ #define F2FS_GOING_DOWN_METAFLUSH 0x3 /* going down with meta flush */ #define F2FS_GOING_DOWN_NEED_FSCK 0x4 /* going down to trigger fsck */ #if defined(__KERNEL__) && defined(CONFIG_COMPAT) /* * ioctl commands in 32 bit emulation */ #define F2FS_IOC32_GETFLAGS FS_IOC32_GETFLAGS #define F2FS_IOC32_SETFLAGS FS_IOC32_SETFLAGS #define F2FS_IOC32_GETVERSION FS_IOC32_GETVERSION #endif #define F2FS_IOC_FSGETXATTR FS_IOC_FSGETXATTR #define F2FS_IOC_FSSETXATTR FS_IOC_FSSETXATTR struct f2fs_gc_range { u32 sync; u64 start; u64 len; }; struct f2fs_defragment { u64 start; u64 len; }; struct f2fs_move_range { u32 dst_fd; /* destination fd */ u64 pos_in; /* start position in src_fd */ u64 pos_out; /* start position in dst_fd */ u64 len; /* size to move */ }; struct f2fs_flush_device { u32 dev_num; /* device number to flush */ u32 segments; /* # of segments to flush */ }; /* for inline stuff */ #define DEF_INLINE_RESERVED_SIZE 1 static inline int get_extra_isize(struct inode *inode); static inline int get_inline_xattr_addrs(struct inode *inode); #define MAX_INLINE_DATA(inode) (sizeof(__le32) * \ (CUR_ADDRS_PER_INODE(inode) - \ get_inline_xattr_addrs(inode) - \ DEF_INLINE_RESERVED_SIZE)) /* for inline dir */ #define NR_INLINE_DENTRY(inode) (MAX_INLINE_DATA(inode) * BITS_PER_BYTE / \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ BITS_PER_BYTE + 1)) #define INLINE_DENTRY_BITMAP_SIZE(inode) \ DIV_ROUND_UP(NR_INLINE_DENTRY(inode), BITS_PER_BYTE) #define INLINE_RESERVED_SIZE(inode) (MAX_INLINE_DATA(inode) - \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ NR_INLINE_DENTRY(inode) + \ INLINE_DENTRY_BITMAP_SIZE(inode))) /* * For INODE and NODE manager */ /* for directory operations */ struct f2fs_dentry_ptr { struct inode *inode; void *bitmap; struct f2fs_dir_entry *dentry; __u8 (*filename)[F2FS_SLOT_LEN]; int max; int nr_bitmap; }; static inline void make_dentry_ptr_block(struct inode *inode, struct f2fs_dentry_ptr *d, struct f2fs_dentry_block *t) { d->inode = inode; d->max = NR_DENTRY_IN_BLOCK; d->nr_bitmap = SIZE_OF_DENTRY_BITMAP; d->bitmap = t->dentry_bitmap; d->dentry = t->dentry; d->filename = t->filename; } static inline void make_dentry_ptr_inline(struct inode *inode, struct f2fs_dentry_ptr *d, void *t) { int entry_cnt = NR_INLINE_DENTRY(inode); int bitmap_size = INLINE_DENTRY_BITMAP_SIZE(inode); int reserved_size = INLINE_RESERVED_SIZE(inode); d->inode = inode; d->max = entry_cnt; d->nr_bitmap = bitmap_size; d->bitmap = t; d->dentry = t + bitmap_size + reserved_size; d->filename = t + bitmap_size + reserved_size + SIZE_OF_DIR_ENTRY * entry_cnt; } /* * XATTR_NODE_OFFSET stores xattrs to one node block per file keeping -1 * as its node offset to distinguish from index node blocks. * But some bits are used to mark the node block. */ #define XATTR_NODE_OFFSET ((((unsigned int)-1) << OFFSET_BIT_SHIFT) \ >> OFFSET_BIT_SHIFT) enum { ALLOC_NODE, /* allocate a new node page if needed */ LOOKUP_NODE, /* look up a node without readahead */ LOOKUP_NODE_RA, /* * look up a node with readahead called * by get_data_block. */ }; #define DEFAULT_RETRY_IO_COUNT 8 /* maximum retry read IO count */ /* maximum retry quota flush count */ #define DEFAULT_RETRY_QUOTA_FLUSH_COUNT 8 #define F2FS_LINK_MAX 0xffffffff /* maximum link count per file */ #define MAX_DIR_RA_PAGES 4 /* maximum ra pages of dir */ /* for in-memory extent cache entry */ #define F2FS_MIN_EXTENT_LEN 64 /* minimum extent length */ /* number of extent info in extent cache we try to shrink */ #define EXTENT_CACHE_SHRINK_NUMBER 128 struct rb_entry { struct rb_node rb_node; /* rb node located in rb-tree */ unsigned int ofs; /* start offset of the entry */ unsigned int len; /* length of the entry */ }; struct extent_info { unsigned int fofs; /* start offset in a file */ unsigned int len; /* length of the extent */ u32 blk; /* start block address of the extent */ }; struct extent_node { struct rb_node rb_node; /* rb node located in rb-tree */ struct extent_info ei; /* extent info */ struct list_head list; /* node in global extent list of sbi */ struct extent_tree *et; /* extent tree pointer */ }; struct extent_tree { nid_t ino; /* inode number */ struct rb_root_cached root; /* root of extent info rb-tree */ struct extent_node *cached_en; /* recently accessed extent node */ struct extent_info largest; /* largested extent info */ struct list_head list; /* to be used by sbi->zombie_list */ rwlock_t lock; /* protect extent info rb-tree */ atomic_t node_cnt; /* # of extent node in rb-tree*/ bool largest_updated; /* largest extent updated */ }; /* * This structure is taken from ext4_map_blocks. * * Note that, however, f2fs uses NEW and MAPPED flags for f2fs_map_blocks(). */ #define F2FS_MAP_NEW (1 << BH_New) #define F2FS_MAP_MAPPED (1 << BH_Mapped) #define F2FS_MAP_UNWRITTEN (1 << BH_Unwritten) #define F2FS_MAP_FLAGS (F2FS_MAP_NEW | F2FS_MAP_MAPPED |\ F2FS_MAP_UNWRITTEN) struct f2fs_map_blocks { block_t m_pblk; block_t m_lblk; unsigned int m_len; unsigned int m_flags; pgoff_t *m_next_pgofs; /* point next possible non-hole pgofs */ pgoff_t *m_next_extent; /* point to next possible extent */ int m_seg_type; bool m_may_create; /* indicate it is from write path */ }; /* for flag in get_data_block */ enum { F2FS_GET_BLOCK_DEFAULT, F2FS_GET_BLOCK_FIEMAP, F2FS_GET_BLOCK_BMAP, F2FS_GET_BLOCK_DIO, F2FS_GET_BLOCK_PRE_DIO, F2FS_GET_BLOCK_PRE_AIO, F2FS_GET_BLOCK_PRECACHE, }; /* * i_advise uses FADVISE_XXX_BIT. We can add additional hints later. */ #define FADVISE_COLD_BIT 0x01 #define FADVISE_LOST_PINO_BIT 0x02 #define FADVISE_ENCRYPT_BIT 0x04 #define FADVISE_ENC_NAME_BIT 0x08 #define FADVISE_KEEP_SIZE_BIT 0x10 #define FADVISE_HOT_BIT 0x20 #define FADVISE_VERITY_BIT 0x40 /* reserved */ #define FADVISE_MODIFIABLE_BITS (FADVISE_COLD_BIT | FADVISE_HOT_BIT) #define file_is_cold(inode) is_file(inode, FADVISE_COLD_BIT) #define file_wrong_pino(inode) is_file(inode, FADVISE_LOST_PINO_BIT) #define file_set_cold(inode) set_file(inode, FADVISE_COLD_BIT) #define file_lost_pino(inode) set_file(inode, FADVISE_LOST_PINO_BIT) #define file_clear_cold(inode) clear_file(inode, FADVISE_COLD_BIT) #define file_got_pino(inode) clear_file(inode, FADVISE_LOST_PINO_BIT) #define file_is_encrypt(inode) is_file(inode, FADVISE_ENCRYPT_BIT) #define file_set_encrypt(inode) set_file(inode, FADVISE_ENCRYPT_BIT) #define file_clear_encrypt(inode) clear_file(inode, FADVISE_ENCRYPT_BIT) #define file_enc_name(inode) is_file(inode, FADVISE_ENC_NAME_BIT) #define file_set_enc_name(inode) set_file(inode, FADVISE_ENC_NAME_BIT) #define file_keep_isize(inode) is_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_set_keep_isize(inode) set_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_is_hot(inode) is_file(inode, FADVISE_HOT_BIT) #define file_set_hot(inode) set_file(inode, FADVISE_HOT_BIT) #define file_clear_hot(inode) clear_file(inode, FADVISE_HOT_BIT) #define DEF_DIR_LEVEL 0 enum { GC_FAILURE_PIN, GC_FAILURE_ATOMIC, MAX_GC_FAILURE }; struct f2fs_inode_info { struct inode vfs_inode; /* serve a vfs inode */ unsigned long i_flags; /* keep an inode flags for ioctl */ unsigned char i_advise; /* use to give file attribute hints */ unsigned char i_dir_level; /* use for dentry level for large dir */ unsigned int i_current_depth; /* only for directory depth */ /* for gc failure statistic */ unsigned int i_gc_failures[MAX_GC_FAILURE]; unsigned int i_pino; /* parent inode number */ umode_t i_acl_mode; /* keep file acl mode temporarily */ /* Use below internally in f2fs*/ unsigned long flags; /* use to pass per-file flags */ struct rw_semaphore i_sem; /* protect fi info */ atomic_t dirty_pages; /* # of dirty pages */ f2fs_hash_t chash; /* hash value of given file name */ unsigned int clevel; /* maximum level of given file name */ struct task_struct *task; /* lookup and create consistency */ struct task_struct *cp_task; /* separate cp/wb IO stats*/ nid_t i_xattr_nid; /* node id that contains xattrs */ loff_t last_disk_size; /* lastly written file size */ #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; /* quota space reservation, managed internally by quota code */ qsize_t i_reserved_quota; #endif struct list_head dirty_list; /* dirty list for dirs and files */ struct list_head gdirty_list; /* linked in global dirty list */ struct list_head inmem_ilist; /* list for inmem inodes */ struct list_head inmem_pages; /* inmemory pages managed by f2fs */ struct task_struct *inmem_task; /* store inmemory task */ struct mutex inmem_lock; /* lock for inmemory pages */ struct extent_tree *extent_tree; /* cached extent_tree entry */ /* avoid racing between foreground op and gc */ struct rw_semaphore i_gc_rwsem[2]; struct rw_semaphore i_mmap_sem; struct rw_semaphore i_xattr_sem; /* avoid racing between reading and changing EAs */ int i_extra_isize; /* size of extra space located in i_addr */ kprojid_t i_projid; /* id for project quota */ int i_inline_xattr_size; /* inline xattr size */ struct timespec64 i_crtime; /* inode creation time */ struct timespec64 i_disk_time[4];/* inode disk times */ }; static inline void get_extent_info(struct extent_info *ext, struct f2fs_extent *i_ext) { ext->fofs = le32_to_cpu(i_ext->fofs); ext->blk = le32_to_cpu(i_ext->blk); ext->len = le32_to_cpu(i_ext->len); } static inline void set_raw_extent(struct extent_info *ext, struct f2fs_extent *i_ext) { i_ext->fofs = cpu_to_le32(ext->fofs); i_ext->blk = cpu_to_le32(ext->blk); i_ext->len = cpu_to_le32(ext->len); } static inline void set_extent_info(struct extent_info *ei, unsigned int fofs, u32 blk, unsigned int len) { ei->fofs = fofs; ei->blk = blk; ei->len = len; } static inline bool __is_discard_mergeable(struct discard_info *back, struct discard_info *front, unsigned int max_len) { return (back->lstart + back->len == front->lstart) && (back->len + front->len <= max_len); } static inline bool __is_discard_back_mergeable(struct discard_info *cur, struct discard_info *back, unsigned int max_len) { return __is_discard_mergeable(back, cur, max_len); } static inline bool __is_discard_front_mergeable(struct discard_info *cur, struct discard_info *front, unsigned int max_len) { return __is_discard_mergeable(cur, front, max_len); } static inline bool __is_extent_mergeable(struct extent_info *back, struct extent_info *front) { return (back->fofs + back->len == front->fofs && back->blk + back->len == front->blk); } static inline bool __is_back_mergeable(struct extent_info *cur, struct extent_info *back) { return __is_extent_mergeable(back, cur); } static inline bool __is_front_mergeable(struct extent_info *cur, struct extent_info *front) { return __is_extent_mergeable(cur, front); } extern void f2fs_mark_inode_dirty_sync(struct inode *inode, bool sync); static inline void __try_update_largest_extent(struct extent_tree *et, struct extent_node *en) { if (en->ei.len > et->largest.len) { et->largest = en->ei; et->largest_updated = true; } } /* * For free nid management */ enum nid_state { FREE_NID, /* newly added to free nid list */ PREALLOC_NID, /* it is preallocated */ MAX_NID_STATE, }; struct f2fs_nm_info { block_t nat_blkaddr; /* base disk address of NAT */ nid_t max_nid; /* maximum possible node ids */ nid_t available_nids; /* # of available node ids */ nid_t next_scan_nid; /* the next nid to be scanned */ unsigned int ram_thresh; /* control the memory footprint */ unsigned int ra_nid_pages; /* # of nid pages to be readaheaded */ unsigned int dirty_nats_ratio; /* control dirty nats ratio threshold */ /* NAT cache management */ struct radix_tree_root nat_root;/* root of the nat entry cache */ struct radix_tree_root nat_set_root;/* root of the nat set cache */ struct rw_semaphore nat_tree_lock; /* protect nat_tree_lock */ struct list_head nat_entries; /* cached nat entry list (clean) */ spinlock_t nat_list_lock; /* protect clean nat entry list */ unsigned int nat_cnt; /* the # of cached nat entries */ unsigned int dirty_nat_cnt; /* total num of nat entries in set */ unsigned int nat_blocks; /* # of nat blocks */ /* free node ids management */ struct radix_tree_root free_nid_root;/* root of the free_nid cache */ struct list_head free_nid_list; /* list for free nids excluding preallocated nids */ unsigned int nid_cnt[MAX_NID_STATE]; /* the number of free node id */ spinlock_t nid_list_lock; /* protect nid lists ops */ struct mutex build_lock; /* lock for build free nids */ unsigned char **free_nid_bitmap; unsigned char *nat_block_bitmap; unsigned short *free_nid_count; /* free nid count of NAT block */ /* for checkpoint */ char *nat_bitmap; /* NAT bitmap pointer */ unsigned int nat_bits_blocks; /* # of nat bits blocks */ unsigned char *nat_bits; /* NAT bits blocks */ unsigned char *full_nat_bits; /* full NAT pages */ unsigned char *empty_nat_bits; /* empty NAT pages */ #ifdef CONFIG_F2FS_CHECK_FS char *nat_bitmap_mir; /* NAT bitmap mirror */ #endif int bitmap_size; /* bitmap size */ }; /* * this structure is used as one of function parameters. * all the information are dedicated to a given direct node block determined * by the data offset in a file. */ struct dnode_of_data { struct inode *inode; /* vfs inode pointer */ struct page *inode_page; /* its inode page, NULL is possible */ struct page *node_page; /* cached direct node page */ nid_t nid; /* node id of the direct node block */ unsigned int ofs_in_node; /* data offset in the node page */ bool inode_page_locked; /* inode page is locked or not */ bool node_changed; /* is node block changed */ char cur_level; /* level of hole node page */ char max_level; /* level of current page located */ block_t data_blkaddr; /* block address of the node block */ }; static inline void set_new_dnode(struct dnode_of_data *dn, struct inode *inode, struct page *ipage, struct page *npage, nid_t nid) { memset(dn, 0, sizeof(*dn)); dn->inode = inode; dn->inode_page = ipage; dn->node_page = npage; dn->nid = nid; } /* * For SIT manager * * By default, there are 6 active log areas across the whole main area. * When considering hot and cold data separation to reduce cleaning overhead, * we split 3 for data logs and 3 for node logs as hot, warm, and cold types, * respectively. * In the current design, you should not change the numbers intentionally. * Instead, as a mount option such as active_logs=x, you can use 2, 4, and 6 * logs individually according to the underlying devices. (default: 6) * Just in case, on-disk layout covers maximum 16 logs that consist of 8 for * data and 8 for node logs. */ #define NR_CURSEG_DATA_TYPE (3) #define NR_CURSEG_NODE_TYPE (3) #define NR_CURSEG_TYPE (NR_CURSEG_DATA_TYPE + NR_CURSEG_NODE_TYPE) enum { CURSEG_HOT_DATA = 0, /* directory entry blocks */ CURSEG_WARM_DATA, /* data blocks */ CURSEG_COLD_DATA, /* multimedia or GCed data blocks */ CURSEG_HOT_NODE, /* direct node blocks of directory files */ CURSEG_WARM_NODE, /* direct node blocks of normal files */ CURSEG_COLD_NODE, /* indirect node blocks */ NO_CHECK_TYPE, }; struct flush_cmd { struct completion wait; struct llist_node llnode; nid_t ino; int ret; }; struct flush_cmd_control { struct task_struct *f2fs_issue_flush; /* flush thread */ wait_queue_head_t flush_wait_queue; /* waiting queue for wake-up */ atomic_t issued_flush; /* # of issued flushes */ atomic_t queued_flush; /* # of queued flushes */ struct llist_head issue_list; /* list for command issue */ struct llist_node *dispatch_list; /* list for command dispatch */ }; struct f2fs_sm_info { struct sit_info *sit_info; /* whole segment information */ struct free_segmap_info *free_info; /* free segment information */ struct dirty_seglist_info *dirty_info; /* dirty segment information */ struct curseg_info *curseg_array; /* active segment information */ struct rw_semaphore curseg_lock; /* for preventing curseg change */ block_t seg0_blkaddr; /* block address of 0'th segment */ block_t main_blkaddr; /* start block address of main area */ block_t ssa_blkaddr; /* start block address of SSA area */ unsigned int segment_count; /* total # of segments */ unsigned int main_segments; /* # of segments in main area */ unsigned int reserved_segments; /* # of reserved segments */ unsigned int ovp_segments; /* # of overprovision segments */ /* a threshold to reclaim prefree segments */ unsigned int rec_prefree_segments; /* for batched trimming */ unsigned int trim_sections; /* # of sections to trim */ struct list_head sit_entry_set; /* sit entry set list */ unsigned int ipu_policy; /* in-place-update policy */ unsigned int min_ipu_util; /* in-place-update threshold */ unsigned int min_fsync_blocks; /* threshold for fsync */ unsigned int min_seq_blocks; /* threshold for sequential blocks */ unsigned int min_hot_blocks; /* threshold for hot block allocation */ unsigned int min_ssr_sections; /* threshold to trigger SSR allocation */ /* for flush command control */ struct flush_cmd_control *fcc_info; /* for discard command control */ struct discard_cmd_control *dcc_info; }; /* * For superblock */ /* * COUNT_TYPE for monitoring * * f2fs monitors the number of several block types such as on-writeback, * dirty dentry blocks, dirty node blocks, and dirty meta blocks. */ #define WB_DATA_TYPE(p) (__is_cp_guaranteed(p) ? F2FS_WB_CP_DATA : F2FS_WB_DATA) enum count_type { F2FS_DIRTY_DENTS, F2FS_DIRTY_DATA, F2FS_DIRTY_QDATA, F2FS_DIRTY_NODES, F2FS_DIRTY_META, F2FS_INMEM_PAGES, F2FS_DIRTY_IMETA, F2FS_WB_CP_DATA, F2FS_WB_DATA, F2FS_RD_DATA, F2FS_RD_NODE, F2FS_RD_META, F2FS_DIO_WRITE, F2FS_DIO_READ, NR_COUNT_TYPE, }; /* * The below are the page types of bios used in submit_bio(). * The available types are: * DATA User data pages. It operates as async mode. * NODE Node pages. It operates as async mode. * META FS metadata pages such as SIT, NAT, CP. * NR_PAGE_TYPE The number of page types. * META_FLUSH Make sure the previous pages are written * with waiting the bio's completion * ... Only can be used with META. */ #define PAGE_TYPE_OF_BIO(type) ((type) > META ? META : (type)) enum page_type { DATA, NODE, META, NR_PAGE_TYPE, META_FLUSH, INMEM, /* the below types are used by tracepoints only. */ INMEM_DROP, INMEM_INVALIDATE, INMEM_REVOKE, IPU, OPU, }; enum temp_type { HOT = 0, /* must be zero for meta bio */ WARM, COLD, NR_TEMP_TYPE, }; enum need_lock_type { LOCK_REQ = 0, LOCK_DONE, LOCK_RETRY, }; enum cp_reason_type { CP_NO_NEEDED, CP_NON_REGULAR, CP_HARDLINK, CP_SB_NEED_CP, CP_WRONG_PINO, CP_NO_SPC_ROLL, CP_NODE_NEED_CP, CP_FASTBOOT_MODE, CP_SPEC_LOG_NUM, CP_RECOVER_DIR, }; enum iostat_type { APP_DIRECT_IO, /* app direct IOs */ APP_BUFFERED_IO, /* app buffered IOs */ APP_WRITE_IO, /* app write IOs */ APP_MAPPED_IO, /* app mapped IOs */ FS_DATA_IO, /* data IOs from kworker/fsync/reclaimer */ FS_NODE_IO, /* node IOs from kworker/fsync/reclaimer */ FS_META_IO, /* meta IOs from kworker/reclaimer */ FS_GC_DATA_IO, /* data IOs from forground gc */ FS_GC_NODE_IO, /* node IOs from forground gc */ FS_CP_DATA_IO, /* data IOs from checkpoint */ FS_CP_NODE_IO, /* node IOs from checkpoint */ FS_CP_META_IO, /* meta IOs from checkpoint */ FS_DISCARD, /* discard */ NR_IO_TYPE, }; struct f2fs_io_info { struct f2fs_sb_info *sbi; /* f2fs_sb_info pointer */ nid_t ino; /* inode number */ enum page_type type; /* contains DATA/NODE/META/META_FLUSH */ enum temp_type temp; /* contains HOT/WARM/COLD */ int op; /* contains REQ_OP_ */ int op_flags; /* req_flag_bits */ block_t new_blkaddr; /* new block address to be written */ block_t old_blkaddr; /* old block address before Cow */ struct page *page; /* page to be written */ struct page *encrypted_page; /* encrypted page */ struct list_head list; /* serialize IOs */ bool submitted; /* indicate IO submission */ int need_lock; /* indicate we need to lock cp_rwsem */ bool in_list; /* indicate fio is in io_list */ bool is_por; /* indicate IO is from recovery or not */ bool retry; /* need to reallocate block address */ enum iostat_type io_type; /* io type */ struct writeback_control *io_wbc; /* writeback control */ struct bio **bio; /* bio for ipu */ sector_t *last_block; /* last block number in bio */ unsigned char version; /* version of the node */ }; #define is_read_io(rw) ((rw) == READ) struct f2fs_bio_info { struct f2fs_sb_info *sbi; /* f2fs superblock */ struct bio *bio; /* bios to merge */ sector_t last_block_in_bio; /* last block number */ struct f2fs_io_info fio; /* store buffered io info. */ struct rw_semaphore io_rwsem; /* blocking op for bio */ spinlock_t io_lock; /* serialize DATA/NODE IOs */ struct list_head io_list; /* track fios */ }; #define FDEV(i) (sbi->devs[i]) #define RDEV(i) (raw_super->devs[i]) struct f2fs_dev_info { struct block_device *bdev; char path[MAX_PATH_LEN]; unsigned int total_segments; block_t start_blk; block_t end_blk; #ifdef CONFIG_BLK_DEV_ZONED unsigned int nr_blkz; /* Total number of zones */ unsigned long *blkz_seq; /* Bitmap indicating sequential zones */ #endif }; enum inode_type { DIR_INODE, /* for dirty dir inode */ FILE_INODE, /* for dirty regular/symlink inode */ DIRTY_META, /* for all dirtied inode metadata */ ATOMIC_FILE, /* for all atomic files */ NR_INODE_TYPE, }; /* for inner inode cache management */ struct inode_management { struct radix_tree_root ino_root; /* ino entry array */ spinlock_t ino_lock; /* for ino entry lock */ struct list_head ino_list; /* inode list head */ unsigned long ino_num; /* number of entries */ }; /* For s_flag in struct f2fs_sb_info */ enum { SBI_IS_DIRTY, /* dirty flag for checkpoint */ SBI_IS_CLOSE, /* specify unmounting */ SBI_NEED_FSCK, /* need fsck.f2fs to fix */ SBI_POR_DOING, /* recovery is doing or not */ SBI_NEED_SB_WRITE, /* need to recover superblock */ SBI_NEED_CP, /* need to checkpoint */ SBI_IS_SHUTDOWN, /* shutdown by ioctl */ SBI_IS_RECOVERED, /* recovered orphan/data */ SBI_CP_DISABLED, /* CP was disabled last mount */ SBI_CP_DISABLED_QUICK, /* CP was disabled quickly */ SBI_QUOTA_NEED_FLUSH, /* need to flush quota info in CP */ SBI_QUOTA_SKIP_FLUSH, /* skip flushing quota in current CP */ SBI_QUOTA_NEED_REPAIR, /* quota file may be corrupted */ SBI_IS_RESIZEFS, /* resizefs is in process */ }; enum { CP_TIME, REQ_TIME, DISCARD_TIME, GC_TIME, DISABLE_TIME, UMOUNT_DISCARD_TIMEOUT, MAX_TIME, }; enum { GC_NORMAL, GC_IDLE_CB, GC_IDLE_GREEDY, GC_URGENT, }; enum { WHINT_MODE_OFF, /* not pass down write hints */ WHINT_MODE_USER, /* try to pass down hints given by users */ WHINT_MODE_FS, /* pass down hints with F2FS policy */ }; enum { ALLOC_MODE_DEFAULT, /* stay default */ ALLOC_MODE_REUSE, /* reuse segments as much as possible */ }; enum fsync_mode { FSYNC_MODE_POSIX, /* fsync follows posix semantics */ FSYNC_MODE_STRICT, /* fsync behaves in line with ext4 */ FSYNC_MODE_NOBARRIER, /* fsync behaves nobarrier based on posix */ }; #ifdef CONFIG_FS_ENCRYPTION #define DUMMY_ENCRYPTION_ENABLED(sbi) \ (unlikely(F2FS_OPTION(sbi).test_dummy_encryption)) #else #define DUMMY_ENCRYPTION_ENABLED(sbi) (0) #endif struct f2fs_sb_info { struct super_block *sb; /* pointer to VFS super block */ struct proc_dir_entry *s_proc; /* proc entry */ struct f2fs_super_block *raw_super; /* raw super block pointer */ struct rw_semaphore sb_lock; /* lock for raw super block */ int valid_super_block; /* valid super block no */ unsigned long s_flag; /* flags for sbi */ struct mutex writepages; /* mutex for writepages() */ #ifdef CONFIG_BLK_DEV_ZONED unsigned int blocks_per_blkz; /* F2FS blocks per zone */ unsigned int log_blocks_per_blkz; /* log2 F2FS blocks per zone */ #endif /* for node-related operations */ struct f2fs_nm_info *nm_info; /* node manager */ struct inode *node_inode; /* cache node blocks */ /* for segment-related operations */ struct f2fs_sm_info *sm_info; /* segment manager */ /* for bio operations */ struct f2fs_bio_info *write_io[NR_PAGE_TYPE]; /* for write bios */ /* keep migration IO order for LFS mode */ struct rw_semaphore io_order_lock; mempool_t *write_io_dummy; /* Dummy pages */ /* for checkpoint */ struct f2fs_checkpoint *ckpt; /* raw checkpoint pointer */ int cur_cp_pack; /* remain current cp pack */ spinlock_t cp_lock; /* for flag in ckpt */ struct inode *meta_inode; /* cache meta blocks */ struct mutex cp_mutex; /* checkpoint procedure lock */ struct rw_semaphore cp_rwsem; /* blocking FS operations */ struct rw_semaphore node_write; /* locking node writes */ struct rw_semaphore node_change; /* locking node change */ wait_queue_head_t cp_wait; unsigned long last_time[MAX_TIME]; /* to store time in jiffies */ long interval_time[MAX_TIME]; /* to store thresholds */ struct inode_management im[MAX_INO_ENTRY]; /* manage inode cache */ spinlock_t fsync_node_lock; /* for node entry lock */ struct list_head fsync_node_list; /* node list head */ unsigned int fsync_seg_id; /* sequence id */ unsigned int fsync_node_num; /* number of node entries */ /* for orphan inode, use 0'th array */ unsigned int max_orphans; /* max orphan inodes */ /* for inode management */ struct list_head inode_list[NR_INODE_TYPE]; /* dirty inode list */ spinlock_t inode_lock[NR_INODE_TYPE]; /* for dirty inode list lock */ struct mutex flush_lock; /* for flush exclusion */ /* for extent tree cache */ struct radix_tree_root extent_tree_root;/* cache extent cache entries */ struct mutex extent_tree_lock; /* locking extent radix tree */ struct list_head extent_list; /* lru list for shrinker */ spinlock_t extent_lock; /* locking extent lru list */ atomic_t total_ext_tree; /* extent tree count */ struct list_head zombie_list; /* extent zombie tree list */ atomic_t total_zombie_tree; /* extent zombie tree count */ atomic_t total_ext_node; /* extent info count */ /* basic filesystem units */ unsigned int log_sectors_per_block; /* log2 sectors per block */ unsigned int log_blocksize; /* log2 block size */ unsigned int blocksize; /* block size */ unsigned int root_ino_num; /* root inode number*/ unsigned int node_ino_num; /* node inode number*/ unsigned int meta_ino_num; /* meta inode number*/ unsigned int log_blocks_per_seg; /* log2 blocks per segment */ unsigned int blocks_per_seg; /* blocks per segment */ unsigned int segs_per_sec; /* segments per section */ unsigned int secs_per_zone; /* sections per zone */ unsigned int total_sections; /* total section count */ struct mutex resize_mutex; /* for resize exclusion */ unsigned int total_node_count; /* total node block count */ unsigned int total_valid_node_count; /* valid node block count */ loff_t max_file_blocks; /* max block index of file */ int dir_level; /* directory level */ int readdir_ra; /* readahead inode in readdir */ block_t user_block_count; /* # of user blocks */ block_t total_valid_block_count; /* # of valid blocks */ block_t discard_blks; /* discard command candidats */ block_t last_valid_block_count; /* for recovery */ block_t reserved_blocks; /* configurable reserved blocks */ block_t current_reserved_blocks; /* current reserved blocks */ /* Additional tracking for no checkpoint mode */ block_t unusable_block_count; /* # of blocks saved by last cp */ unsigned int nquota_files; /* # of quota sysfile */ struct rw_semaphore quota_sem; /* blocking cp for flags */ /* # of pages, see count_type */ atomic_t nr_pages[NR_COUNT_TYPE]; /* # of allocated blocks */ struct percpu_counter alloc_valid_block_count; /* writeback control */ atomic_t wb_sync_req[META]; /* count # of WB_SYNC threads */ /* valid inode count */ struct percpu_counter total_valid_inode_count; struct f2fs_mount_info mount_opt; /* mount options */ /* for cleaning operations */ struct mutex gc_mutex; /* mutex for GC */ struct f2fs_gc_kthread *gc_thread; /* GC thread */ unsigned int cur_victim_sec; /* current victim section num */ unsigned int gc_mode; /* current GC state */ unsigned int next_victim_seg[2]; /* next segment in victim section */ /* for skip statistic */ unsigned long long skipped_atomic_files[2]; /* FG_GC and BG_GC */ unsigned long long skipped_gc_rwsem; /* FG_GC only */ /* threshold for gc trials on pinned files */ u64 gc_pin_file_threshold; /* maximum # of trials to find a victim segment for SSR and GC */ unsigned int max_victim_search; /* migration granularity of garbage collection, unit: segment */ unsigned int migration_granularity; /* * for stat information. * one is for the LFS mode, and the other is for the SSR mode. */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info *stat_info; /* FS status information */ atomic_t meta_count[META_MAX]; /* # of meta blocks */ unsigned int segment_count[2]; /* # of allocated segments */ unsigned int block_count[2]; /* # of allocated blocks */ atomic_t inplace_count; /* # of inplace update */ atomic64_t total_hit_ext; /* # of lookup extent cache */ atomic64_t read_hit_rbtree; /* # of hit rbtree extent node */ atomic64_t read_hit_largest; /* # of hit largest extent node */ atomic64_t read_hit_cached; /* # of hit cached extent node */ atomic_t inline_xattr; /* # of inline_xattr inodes */ atomic_t inline_inode; /* # of inline_data inodes */ atomic_t inline_dir; /* # of inline_dentry inodes */ atomic_t aw_cnt; /* # of atomic writes */ atomic_t vw_cnt; /* # of volatile writes */ atomic_t max_aw_cnt; /* max # of atomic writes */ atomic_t max_vw_cnt; /* max # of volatile writes */ int bg_gc; /* background gc calls */ unsigned int io_skip_bggc; /* skip background gc for in-flight IO */ unsigned int other_skip_bggc; /* skip background gc for other reasons */ unsigned int ndirty_inode[NR_INODE_TYPE]; /* # of dirty inodes */ #endif spinlock_t stat_lock; /* lock for stat operations */ /* For app/fs IO statistics */ spinlock_t iostat_lock; unsigned long long write_iostat[NR_IO_TYPE]; bool iostat_enable; /* For sysfs suppport */ struct kobject s_kobj; struct completion s_kobj_unregister; /* For shrinker support */ struct list_head s_list; int s_ndevs; /* number of devices */ struct f2fs_dev_info *devs; /* for device list */ unsigned int dirty_device; /* for checkpoint data flush */ spinlock_t dev_lock; /* protect dirty_device */ struct mutex umount_mutex; unsigned int shrinker_run_no; /* For write statistics */ u64 sectors_written_start; u64 kbytes_written; /* Reference to checksum algorithm driver via cryptoapi */ struct crypto_shash *s_chksum_driver; /* Precomputed FS UUID checksum for seeding other checksums */ __u32 s_chksum_seed; }; struct f2fs_private_dio { struct inode *inode; void *orig_private; bio_end_io_t *orig_end_io; bool write; }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define f2fs_show_injection_info(type) \ printk_ratelimited("%sF2FS-fs : inject %s in %s of %pS\n", \ KERN_INFO, f2fs_fault_name[type], \ __func__, __builtin_return_address(0)) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info; if (!ffi->inject_rate) return false; if (!IS_FAULT_SET(ffi, type)) return false; atomic_inc(&ffi->inject_ops); if (atomic_read(&ffi->inject_ops) >= ffi->inject_rate) { atomic_set(&ffi->inject_ops, 0); return true; } return false; } #else #define f2fs_show_injection_info(type) do { } while (0) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { return false; } #endif /* * Test if the mounted volume is a multi-device volume. * - For a single regular disk volume, sbi->s_ndevs is 0. * - For a single zoned disk volume, sbi->s_ndevs is 1. * - For a multi-device volume, sbi->s_ndevs is always 2 or more. */ static inline bool f2fs_is_multi_device(struct f2fs_sb_info *sbi) { return sbi->s_ndevs > 1; } /* For write statistics. Suppose sector size is 512 bytes, * and the return value is in kbytes. s is of struct f2fs_sb_info. */ #define BD_PART_WRITTEN(s) \ (((u64)part_stat_read((s)->sb->s_bdev->bd_part, sectors[STAT_WRITE]) - \ (s)->sectors_written_start) >> 1) static inline void f2fs_update_time(struct f2fs_sb_info *sbi, int type) { unsigned long now = jiffies; sbi->last_time[type] = now; /* DISCARD_TIME and GC_TIME are based on REQ_TIME */ if (type == REQ_TIME) { sbi->last_time[DISCARD_TIME] = now; sbi->last_time[GC_TIME] = now; } } static inline bool f2fs_time_over(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; return time_after(jiffies, sbi->last_time[type] + interval); } static inline unsigned int f2fs_time_to_wait(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; unsigned int wait_ms = 0; long delta; delta = (sbi->last_time[type] + interval) - jiffies; if (delta > 0) wait_ms = jiffies_to_msecs(delta); return wait_ms; } /* * Inline functions */ static inline u32 __f2fs_crc32(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { struct { struct shash_desc shash; char ctx[4]; } desc; int err; BUG_ON(crypto_shash_descsize(sbi->s_chksum_driver) != sizeof(desc.ctx)); desc.shash.tfm = sbi->s_chksum_driver; *(u32 *)desc.ctx = crc; err = crypto_shash_update(&desc.shash, address, length); BUG_ON(err); return *(u32 *)desc.ctx; } static inline u32 f2fs_crc32(struct f2fs_sb_info *sbi, const void *address, unsigned int length) { return __f2fs_crc32(sbi, F2FS_SUPER_MAGIC, address, length); } static inline bool f2fs_crc_valid(struct f2fs_sb_info *sbi, __u32 blk_crc, void *buf, size_t buf_size) { return f2fs_crc32(sbi, buf, buf_size) == blk_crc; } static inline u32 f2fs_chksum(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { return __f2fs_crc32(sbi, crc, address, length); } static inline struct f2fs_inode_info *F2FS_I(struct inode *inode) { return container_of(inode, struct f2fs_inode_info, vfs_inode); } static inline struct f2fs_sb_info *F2FS_SB(struct super_block *sb) { return sb->s_fs_info; } static inline struct f2fs_sb_info *F2FS_I_SB(struct inode *inode) { return F2FS_SB(inode->i_sb); } static inline struct f2fs_sb_info *F2FS_M_SB(struct address_space *mapping) { return F2FS_I_SB(mapping->host); } static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page_file_mapping(page)); } static inline struct f2fs_super_block *F2FS_RAW_SUPER(struct f2fs_sb_info *sbi) { return (struct f2fs_super_block *)(sbi->raw_super); } static inline struct f2fs_checkpoint *F2FS_CKPT(struct f2fs_sb_info *sbi) { return (struct f2fs_checkpoint *)(sbi->ckpt); } static inline struct f2fs_node *F2FS_NODE(struct page *page) { return (struct f2fs_node *)page_address(page); } static inline struct f2fs_inode *F2FS_INODE(struct page *page) { return &((struct f2fs_node *)page_address(page))->i; } static inline struct f2fs_nm_info *NM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_nm_info *)(sbi->nm_info); } static inline struct f2fs_sm_info *SM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_sm_info *)(sbi->sm_info); } static inline struct sit_info *SIT_I(struct f2fs_sb_info *sbi) { return (struct sit_info *)(SM_I(sbi)->sit_info); } static inline struct free_segmap_info *FREE_I(struct f2fs_sb_info *sbi) { return (struct free_segmap_info *)(SM_I(sbi)->free_info); } static inline struct dirty_seglist_info *DIRTY_I(struct f2fs_sb_info *sbi) { return (struct dirty_seglist_info *)(SM_I(sbi)->dirty_info); } static inline struct address_space *META_MAPPING(struct f2fs_sb_info *sbi) { return sbi->meta_inode->i_mapping; } static inline struct address_space *NODE_MAPPING(struct f2fs_sb_info *sbi) { return sbi->node_inode->i_mapping; } static inline bool is_sbi_flag_set(struct f2fs_sb_info *sbi, unsigned int type) { return test_bit(type, &sbi->s_flag); } static inline void set_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { set_bit(type, &sbi->s_flag); } static inline void clear_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { clear_bit(type, &sbi->s_flag); } static inline unsigned long long cur_cp_version(struct f2fs_checkpoint *cp) { return le64_to_cpu(cp->checkpoint_ver); } static inline unsigned long f2fs_qf_ino(struct super_block *sb, int type) { if (type < F2FS_MAX_QUOTAS) return le32_to_cpu(F2FS_SB(sb)->raw_super->qf_ino[type]); return 0; } static inline __u64 cur_cp_crc(struct f2fs_checkpoint *cp) { size_t crc_offset = le32_to_cpu(cp->checksum_offset); return le32_to_cpu(*((__le32 *)((unsigned char *)cp + crc_offset))); } static inline bool __is_set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags = le32_to_cpu(cp->ckpt_flags); return ckpt_flags & f; } static inline bool is_set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { return __is_set_ckpt_flags(F2FS_CKPT(sbi), f); } static inline void __set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags |= f; cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __set_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void __clear_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags &= (~f); cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void clear_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void disable_nat_bits(struct f2fs_sb_info *sbi, bool lock) { unsigned long flags; /* * In order to re-enable nat_bits we need to call fsck.f2fs by * set_sbi_flag(sbi, SBI_NEED_FSCK). But it may give huge cost, * so let's rely on regular fsck or unclean shutdown. */ if (lock) spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), CP_NAT_BITS_FLAG); kvfree(NM_I(sbi)->nat_bits); NM_I(sbi)->nat_bits = NULL; if (lock) spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline bool enabled_nat_bits(struct f2fs_sb_info *sbi, struct cp_control *cpc) { bool set = is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG); return (cpc) ? (cpc->reason & CP_UMOUNT) && set : set; } static inline void f2fs_lock_op(struct f2fs_sb_info *sbi) { down_read(&sbi->cp_rwsem); } static inline int f2fs_trylock_op(struct f2fs_sb_info *sbi) { return down_read_trylock(&sbi->cp_rwsem); } static inline void f2fs_unlock_op(struct f2fs_sb_info *sbi) { up_read(&sbi->cp_rwsem); } static inline void f2fs_lock_all(struct f2fs_sb_info *sbi) { down_write(&sbi->cp_rwsem); } static inline void f2fs_unlock_all(struct f2fs_sb_info *sbi) { up_write(&sbi->cp_rwsem); } static inline int __get_cp_reason(struct f2fs_sb_info *sbi) { int reason = CP_SYNC; if (test_opt(sbi, FASTBOOT)) reason = CP_FASTBOOT; if (is_sbi_flag_set(sbi, SBI_IS_CLOSE)) reason = CP_UMOUNT; return reason; } static inline bool __remain_node_summaries(int reason) { return (reason & (CP_UMOUNT | CP_FASTBOOT)); } static inline bool __exist_node_summaries(struct f2fs_sb_info *sbi) { return (is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG) || is_set_ckpt_flags(sbi, CP_FASTBOOT_FLAG)); } /* * Check whether the inode has blocks or not */ static inline int F2FS_HAS_BLOCKS(struct inode *inode) { block_t xattr_block = F2FS_I(inode)->i_xattr_nid ? 1 : 0; return (inode->i_blocks >> F2FS_LOG_SECTORS_PER_BLOCK) > xattr_block; } static inline bool f2fs_has_xattr_block(unsigned int ofs) { return ofs == XATTR_NODE_OFFSET; } static inline bool __allow_reserved_blocks(struct f2fs_sb_info *sbi, struct inode *inode, bool cap) { if (!inode) return true; if (!test_opt(sbi, RESERVE_ROOT)) return false; if (IS_NOQUOTA(inode)) return true; if (uid_eq(F2FS_OPTION(sbi).s_resuid, current_fsuid())) return true; if (!gid_eq(F2FS_OPTION(sbi).s_resgid, GLOBAL_ROOT_GID) && in_group_p(F2FS_OPTION(sbi).s_resgid)) return true; if (cap && capable(CAP_SYS_RESOURCE)) return true; return false; } static inline void f2fs_i_blocks_write(struct inode *, block_t, bool, bool); static inline int inc_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, blkcnt_t *count) { blkcnt_t diff = 0, release = 0; block_t avail_user_block_count; int ret; ret = dquot_reserve_block(inode, *count); if (ret) return ret; if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); release = *count; goto enospc; } /* * let's increase this in prior to actual block count change in order * for f2fs_sync_file to avoid data races when deciding checkpoint. */ percpu_counter_add(&sbi->alloc_valid_block_count, (*count)); spin_lock(&sbi->stat_lock); sbi->total_valid_block_count += (block_t)(*count); avail_user_block_count = sbi->user_block_count - sbi->current_reserved_blocks; if (!__allow_reserved_blocks(sbi, inode, true)) avail_user_block_count -= F2FS_OPTION(sbi).root_reserved_blocks; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) { if (avail_user_block_count > sbi->unusable_block_count) avail_user_block_count -= sbi->unusable_block_count; else avail_user_block_count = 0; } if (unlikely(sbi->total_valid_block_count > avail_user_block_count)) { diff = sbi->total_valid_block_count - avail_user_block_count; if (diff > *count) diff = *count; *count -= diff; release = diff; sbi->total_valid_block_count -= diff; if (!*count) { spin_unlock(&sbi->stat_lock); goto enospc; } } spin_unlock(&sbi->stat_lock); if (unlikely(release)) { percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); } f2fs_i_blocks_write(inode, *count, true, true); return 0; enospc: percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); return -ENOSPC; } __printf(2, 3) void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...); #define f2fs_err(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_ERR fmt, ##__VA_ARGS__) #define f2fs_warn(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_WARNING fmt, ##__VA_ARGS__) #define f2fs_notice(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_NOTICE fmt, ##__VA_ARGS__) #define f2fs_info(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_INFO fmt, ##__VA_ARGS__) #define f2fs_debug(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_DEBUG fmt, ##__VA_ARGS__) static inline void dec_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, block_t count) { blkcnt_t sectors = count << F2FS_LOG_SECTORS_PER_BLOCK; spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, sbi->total_valid_block_count < (block_t) count); sbi->total_valid_block_count -= (block_t)count; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks = min(sbi->reserved_blocks, sbi->current_reserved_blocks + count); spin_unlock(&sbi->stat_lock); if (unlikely(inode->i_blocks < sectors)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu, sectors:%llu", inode->i_ino, (unsigned long long)inode->i_blocks, (unsigned long long)sectors); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, count, false, true); } static inline void inc_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_inc(&sbi->nr_pages[count_type]); if (count_type == F2FS_DIRTY_DENTS || count_type == F2FS_DIRTY_NODES || count_type == F2FS_DIRTY_META || count_type == F2FS_DIRTY_QDATA || count_type == F2FS_DIRTY_IMETA) set_sbi_flag(sbi, SBI_IS_DIRTY); } static inline void inode_inc_dirty_pages(struct inode *inode) { atomic_inc(&F2FS_I(inode)->dirty_pages); inc_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) inc_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline void dec_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_dec(&sbi->nr_pages[count_type]); } static inline void inode_dec_dirty_pages(struct inode *inode) { if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) && !S_ISLNK(inode->i_mode)) return; atomic_dec(&F2FS_I(inode)->dirty_pages); dec_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) dec_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline s64 get_pages(struct f2fs_sb_info *sbi, int count_type) { return atomic_read(&sbi->nr_pages[count_type]); } static inline int get_dirty_pages(struct inode *inode) { return atomic_read(&F2FS_I(inode)->dirty_pages); } static inline int get_blocktype_secs(struct f2fs_sb_info *sbi, int block_type) { unsigned int pages_per_sec = sbi->segs_per_sec * sbi->blocks_per_seg; unsigned int segs = (get_pages(sbi, block_type) + pages_per_sec - 1) >> sbi->log_blocks_per_seg; return segs / sbi->segs_per_sec; } static inline block_t valid_user_blocks(struct f2fs_sb_info *sbi) { return sbi->total_valid_block_count; } static inline block_t discard_blocks(struct f2fs_sb_info *sbi) { return sbi->discard_blks; } static inline unsigned long __bitmap_size(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); /* return NAT or SIT bitmap */ if (flag == NAT_BITMAP) return le32_to_cpu(ckpt->nat_ver_bitmap_bytesize); else if (flag == SIT_BITMAP) return le32_to_cpu(ckpt->sit_ver_bitmap_bytesize); return 0; } static inline block_t __cp_payload(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_payload); } static inline void *__bitmap_ptr(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); int offset; if (is_set_ckpt_flags(sbi, CP_LARGE_NAT_BITMAP_FLAG)) { offset = (flag == SIT_BITMAP) ? le32_to_cpu(ckpt->nat_ver_bitmap_bytesize) : 0; /* * if large_nat_bitmap feature is enabled, leave checksum * protection for all nat/sit bitmaps. */ return &ckpt->sit_nat_version_bitmap + offset + sizeof(__le32); } if (__cp_payload(sbi) > 0) { if (flag == NAT_BITMAP) return &ckpt->sit_nat_version_bitmap; else return (unsigned char *)ckpt + F2FS_BLKSIZE; } else { offset = (flag == NAT_BITMAP) ? le32_to_cpu(ckpt->sit_ver_bitmap_bytesize) : 0; return &ckpt->sit_nat_version_bitmap + offset; } } static inline block_t __start_cp_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 2) start_addr += sbi->blocks_per_seg; return start_addr; } static inline block_t __start_cp_next_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 1) start_addr += sbi->blocks_per_seg; return start_addr; } static inline void __set_cp_next_pack(struct f2fs_sb_info *sbi) { sbi->cur_cp_pack = (sbi->cur_cp_pack == 1) ? 2 : 1; } static inline block_t __start_sum_addr(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_CKPT(sbi)->cp_pack_start_sum); } static inline int inc_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { block_t valid_block_count; unsigned int valid_node_count, user_block_count; int err; if (is_inode) { if (inode) { err = dquot_alloc_inode(inode); if (err) return err; } } else { err = dquot_reserve_block(inode, 1); if (err) return err; } if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); goto enospc; } spin_lock(&sbi->stat_lock); valid_block_count = sbi->total_valid_block_count + sbi->current_reserved_blocks + 1; if (!__allow_reserved_blocks(sbi, inode, false)) valid_block_count += F2FS_OPTION(sbi).root_reserved_blocks; user_block_count = sbi->user_block_count; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) user_block_count -= sbi->unusable_block_count; if (unlikely(valid_block_count > user_block_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } valid_node_count = sbi->total_valid_node_count + 1; if (unlikely(valid_node_count > sbi->total_node_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } sbi->total_valid_node_count++; sbi->total_valid_block_count++; spin_unlock(&sbi->stat_lock); if (inode) { if (is_inode) f2fs_mark_inode_dirty_sync(inode, true); else f2fs_i_blocks_write(inode, 1, true, true); } percpu_counter_inc(&sbi->alloc_valid_block_count); return 0; enospc: if (is_inode) { if (inode) dquot_free_inode(inode); } else { dquot_release_reservation_block(inode, 1); } return -ENOSPC; } static inline void dec_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, !sbi->total_valid_block_count); f2fs_bug_on(sbi, !sbi->total_valid_node_count); sbi->total_valid_node_count--; sbi->total_valid_block_count--; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks++; spin_unlock(&sbi->stat_lock); if (is_inode) { dquot_free_inode(inode); } else { if (unlikely(inode->i_blocks == 0)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu", inode->i_ino, (unsigned long long)inode->i_blocks); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, 1, false, true); } } static inline unsigned int valid_node_count(struct f2fs_sb_info *sbi) { return sbi->total_valid_node_count; } static inline void inc_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_inc(&sbi->total_valid_inode_count); } static inline void dec_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_dec(&sbi->total_valid_inode_count); } static inline s64 valid_inode_count(struct f2fs_sb_info *sbi) { return percpu_counter_sum_positive(&sbi->total_valid_inode_count); } static inline struct page *f2fs_grab_cache_page(struct address_space *mapping, pgoff_t index, bool for_write) { struct page *page; if (IS_ENABLED(CONFIG_F2FS_FAULT_INJECTION)) { if (!for_write) page = find_get_page_flags(mapping, index, FGP_LOCK | FGP_ACCESSED); else page = find_lock_page(mapping, index); if (page) return page; if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_ALLOC)) { f2fs_show_injection_info(FAULT_PAGE_ALLOC); return NULL; } } if (!for_write) return grab_cache_page(mapping, index); return grab_cache_page_write_begin(mapping, index, AOP_FLAG_NOFS); } static inline struct page *f2fs_pagecache_get_page( struct address_space *mapping, pgoff_t index, int fgp_flags, gfp_t gfp_mask) { if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_GET)) { f2fs_show_injection_info(FAULT_PAGE_GET); return NULL; } return pagecache_get_page(mapping, index, fgp_flags, gfp_mask); } static inline void f2fs_copy_page(struct page *src, struct page *dst) { char *src_kaddr = kmap(src); char *dst_kaddr = kmap(dst); memcpy(dst_kaddr, src_kaddr, PAGE_SIZE); kunmap(dst); kunmap(src); } static inline void f2fs_put_page(struct page *page, int unlock) { if (!page) return; if (unlock) { f2fs_bug_on(F2FS_P_SB(page), !PageLocked(page)); unlock_page(page); } put_page(page); } static inline void f2fs_put_dnode(struct dnode_of_data *dn) { if (dn->node_page) f2fs_put_page(dn->node_page, 1); if (dn->inode_page && dn->node_page != dn->inode_page) f2fs_put_page(dn->inode_page, 0); dn->node_page = NULL; dn->inode_page = NULL; } static inline struct kmem_cache *f2fs_kmem_cache_create(const char *name, size_t size) { return kmem_cache_create(name, size, 0, SLAB_RECLAIM_ACCOUNT, NULL); } static inline void *f2fs_kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags) { void *entry; entry = kmem_cache_alloc(cachep, flags); if (!entry) entry = kmem_cache_alloc(cachep, flags | __GFP_NOFAIL); return entry; } static inline struct bio *f2fs_bio_alloc(struct f2fs_sb_info *sbi, int npages, bool no_fail) { struct bio *bio; if (no_fail) { /* No failure on bio allocation */ bio = bio_alloc(GFP_NOIO, npages); if (!bio) bio = bio_alloc(GFP_NOIO | __GFP_NOFAIL, npages); return bio; } if (time_to_inject(sbi, FAULT_ALLOC_BIO)) { f2fs_show_injection_info(FAULT_ALLOC_BIO); return NULL; } return bio_alloc(GFP_KERNEL, npages); } static inline bool is_idle(struct f2fs_sb_info *sbi, int type) { if (sbi->gc_mode == GC_URGENT) return true; if (get_pages(sbi, F2FS_RD_DATA) || get_pages(sbi, F2FS_RD_NODE) || get_pages(sbi, F2FS_RD_META) || get_pages(sbi, F2FS_WB_DATA) || get_pages(sbi, F2FS_WB_CP_DATA) || get_pages(sbi, F2FS_DIO_READ) || get_pages(sbi, F2FS_DIO_WRITE)) return false; if (type != DISCARD_TIME && SM_I(sbi) && SM_I(sbi)->dcc_info && atomic_read(&SM_I(sbi)->dcc_info->queued_discard)) return false; if (SM_I(sbi) && SM_I(sbi)->fcc_info && atomic_read(&SM_I(sbi)->fcc_info->queued_flush)) return false; return f2fs_time_over(sbi, type); } static inline void f2fs_radix_tree_insert(struct radix_tree_root *root, unsigned long index, void *item) { while (radix_tree_insert(root, index, item)) cond_resched(); } #define RAW_IS_INODE(p) ((p)->footer.nid == (p)->footer.ino) static inline bool IS_INODE(struct page *page) { struct f2fs_node *p = F2FS_NODE(page); return RAW_IS_INODE(p); } static inline int offset_in_addr(struct f2fs_inode *i) { return (i->i_inline & F2FS_EXTRA_ATTR) ? (le16_to_cpu(i->i_extra_isize) / sizeof(__le32)) : 0; } static inline __le32 *blkaddr_in_node(struct f2fs_node *node) { return RAW_IS_INODE(node) ? node->i.i_addr : node->dn.addr; } static inline int f2fs_has_extra_attr(struct inode *inode); static inline block_t datablock_addr(struct inode *inode, struct page *node_page, unsigned int offset) { struct f2fs_node *raw_node; __le32 *addr_array; int base = 0; bool is_inode = IS_INODE(node_page); raw_node = F2FS_NODE(node_page); /* from GC path only */ if (is_inode) { if (!inode) base = offset_in_addr(&raw_node->i); else if (f2fs_has_extra_attr(inode)) base = get_extra_isize(inode); } addr_array = blkaddr_in_node(raw_node); return le32_to_cpu(addr_array[base + offset]); } static inline int f2fs_test_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); return mask & *addr; } static inline void f2fs_set_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr |= mask; } static inline void f2fs_clear_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr &= ~mask; } static inline int f2fs_test_and_set_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr |= mask; return ret; } static inline int f2fs_test_and_clear_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr &= ~mask; return ret; } static inline void f2fs_change_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr ^= mask; } /* * On-disk inode flags (f2fs_inode::i_flags) */ #define F2FS_SYNC_FL 0x00000008 /* Synchronous updates */ #define F2FS_IMMUTABLE_FL 0x00000010 /* Immutable file */ #define F2FS_APPEND_FL 0x00000020 /* writes to file may only append */ #define F2FS_NODUMP_FL 0x00000040 /* do not dump file */ #define F2FS_NOATIME_FL 0x00000080 /* do not update atime */ #define F2FS_INDEX_FL 0x00001000 /* hash-indexed directory */ #define F2FS_DIRSYNC_FL 0x00010000 /* dirsync behaviour (directories only) */ #define F2FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */ /* Flags that should be inherited by new inodes from their parent. */ #define F2FS_FL_INHERITED (F2FS_SYNC_FL | F2FS_NODUMP_FL | F2FS_NOATIME_FL | \ F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL) /* Flags that are appropriate for regular files (all but dir-specific ones). */ #define F2FS_REG_FLMASK (~(F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL)) /* Flags that are appropriate for non-directories/regular files. */ #define F2FS_OTHER_FLMASK (F2FS_NODUMP_FL | F2FS_NOATIME_FL) static inline __u32 f2fs_mask_flags(umode_t mode, __u32 flags) { if (S_ISDIR(mode)) return flags; else if (S_ISREG(mode)) return flags & F2FS_REG_FLMASK; else return flags & F2FS_OTHER_FLMASK; } /* used for f2fs_inode_info->flags */ enum { FI_NEW_INODE, /* indicate newly allocated inode */ FI_DIRTY_INODE, /* indicate inode is dirty or not */ FI_AUTO_RECOVER, /* indicate inode is recoverable */ FI_DIRTY_DIR, /* indicate directory has dirty pages */ FI_INC_LINK, /* need to increment i_nlink */ FI_ACL_MODE, /* indicate acl mode */ FI_NO_ALLOC, /* should not allocate any blocks */ FI_FREE_NID, /* free allocated nide */ FI_NO_EXTENT, /* not to use the extent cache */ FI_INLINE_XATTR, /* used for inline xattr */ FI_INLINE_DATA, /* used for inline data*/ FI_INLINE_DENTRY, /* used for inline dentry */ FI_APPEND_WRITE, /* inode has appended data */ FI_UPDATE_WRITE, /* inode has in-place-update data */ FI_NEED_IPU, /* used for ipu per file */ FI_ATOMIC_FILE, /* indicate atomic file */ FI_ATOMIC_COMMIT, /* indicate the state of atomical committing */ FI_VOLATILE_FILE, /* indicate volatile file */ FI_FIRST_BLOCK_WRITTEN, /* indicate #0 data block was written */ FI_DROP_CACHE, /* drop dirty page cache */ FI_DATA_EXIST, /* indicate data exists */ FI_INLINE_DOTS, /* indicate inline dot dentries */ FI_DO_DEFRAG, /* indicate defragment is running */ FI_DIRTY_FILE, /* indicate regular/symlink has dirty pages */ FI_NO_PREALLOC, /* indicate skipped preallocated blocks */ FI_HOT_DATA, /* indicate file is hot */ FI_EXTRA_ATTR, /* indicate file has extra attribute */ FI_PROJ_INHERIT, /* indicate file inherits projectid */ FI_PIN_FILE, /* indicate file should not be gced */ FI_ATOMIC_REVOKE_REQUEST, /* request to drop atomic data */ }; static inline void __mark_inode_dirty_flag(struct inode *inode, int flag, bool set) { switch (flag) { case FI_INLINE_XATTR: case FI_INLINE_DATA: case FI_INLINE_DENTRY: case FI_NEW_INODE: if (set) return; /* fall through */ case FI_DATA_EXIST: case FI_INLINE_DOTS: case FI_PIN_FILE: f2fs_mark_inode_dirty_sync(inode, true); } } static inline void set_inode_flag(struct inode *inode, int flag) { if (!test_bit(flag, &F2FS_I(inode)->flags)) set_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, true); } static inline int is_inode_flag_set(struct inode *inode, int flag) { return test_bit(flag, &F2FS_I(inode)->flags); } static inline void clear_inode_flag(struct inode *inode, int flag) { if (test_bit(flag, &F2FS_I(inode)->flags)) clear_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, false); } static inline void set_acl_inode(struct inode *inode, umode_t mode) { F2FS_I(inode)->i_acl_mode = mode; set_inode_flag(inode, FI_ACL_MODE); f2fs_mark_inode_dirty_sync(inode, false); } static inline void f2fs_i_links_write(struct inode *inode, bool inc) { if (inc) inc_nlink(inode); else drop_nlink(inode); f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_blocks_write(struct inode *inode, block_t diff, bool add, bool claim) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); /* add = 1, claim = 1 should be dquot_reserve_block in pair */ if (add) { if (claim) dquot_claim_block(inode, diff); else dquot_alloc_block_nofail(inode, diff); } else { dquot_free_block(inode, diff); } f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_size_write(struct inode *inode, loff_t i_size) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); if (i_size_read(inode) == i_size) return; i_size_write(inode, i_size); f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_depth_write(struct inode *inode, unsigned int depth) { F2FS_I(inode)->i_current_depth = depth; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_gc_failures_write(struct inode *inode, unsigned int count) { F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN] = count; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_xnid_write(struct inode *inode, nid_t xnid) { F2FS_I(inode)->i_xattr_nid = xnid; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_pino_write(struct inode *inode, nid_t pino) { F2FS_I(inode)->i_pino = pino; f2fs_mark_inode_dirty_sync(inode, true); } static inline void get_inline_info(struct inode *inode, struct f2fs_inode *ri) { struct f2fs_inode_info *fi = F2FS_I(inode); if (ri->i_inline & F2FS_INLINE_XATTR) set_bit(FI_INLINE_XATTR, &fi->flags); if (ri->i_inline & F2FS_INLINE_DATA) set_bit(FI_INLINE_DATA, &fi->flags); if (ri->i_inline & F2FS_INLINE_DENTRY) set_bit(FI_INLINE_DENTRY, &fi->flags); if (ri->i_inline & F2FS_DATA_EXIST) set_bit(FI_DATA_EXIST, &fi->flags); if (ri->i_inline & F2FS_INLINE_DOTS) set_bit(FI_INLINE_DOTS, &fi->flags); if (ri->i_inline & F2FS_EXTRA_ATTR) set_bit(FI_EXTRA_ATTR, &fi->flags); if (ri->i_inline & F2FS_PIN_FILE) set_bit(FI_PIN_FILE, &fi->flags); } static inline void set_raw_inline(struct inode *inode, struct f2fs_inode *ri) { ri->i_inline = 0; if (is_inode_flag_set(inode, FI_INLINE_XATTR)) ri->i_inline |= F2FS_INLINE_XATTR; if (is_inode_flag_set(inode, FI_INLINE_DATA)) ri->i_inline |= F2FS_INLINE_DATA; if (is_inode_flag_set(inode, FI_INLINE_DENTRY)) ri->i_inline |= F2FS_INLINE_DENTRY; if (is_inode_flag_set(inode, FI_DATA_EXIST)) ri->i_inline |= F2FS_DATA_EXIST; if (is_inode_flag_set(inode, FI_INLINE_DOTS)) ri->i_inline |= F2FS_INLINE_DOTS; if (is_inode_flag_set(inode, FI_EXTRA_ATTR)) ri->i_inline |= F2FS_EXTRA_ATTR; if (is_inode_flag_set(inode, FI_PIN_FILE)) ri->i_inline |= F2FS_PIN_FILE; } static inline int f2fs_has_extra_attr(struct inode *inode) { return is_inode_flag_set(inode, FI_EXTRA_ATTR); } static inline int f2fs_has_inline_xattr(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_XATTR); } static inline unsigned int addrs_per_inode(struct inode *inode) { unsigned int addrs = CUR_ADDRS_PER_INODE(inode) - get_inline_xattr_addrs(inode); return ALIGN_DOWN(addrs, 1); } static inline unsigned int addrs_per_block(struct inode *inode) { return ALIGN_DOWN(DEF_ADDRS_PER_BLOCK, 1); } static inline void *inline_xattr_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); return (void *)&(ri->i_addr[DEF_ADDRS_PER_INODE - get_inline_xattr_addrs(inode)]); } static inline int inline_xattr_size(struct inode *inode) { if (f2fs_has_inline_xattr(inode)) return get_inline_xattr_addrs(inode) * sizeof(__le32); return 0; } static inline int f2fs_has_inline_data(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DATA); } static inline int f2fs_exist_data(struct inode *inode) { return is_inode_flag_set(inode, FI_DATA_EXIST); } static inline int f2fs_has_inline_dots(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DOTS); } static inline bool f2fs_is_pinned_file(struct inode *inode) { return is_inode_flag_set(inode, FI_PIN_FILE); } static inline bool f2fs_is_atomic_file(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_FILE); } static inline bool f2fs_is_commit_atomic_write(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_COMMIT); } static inline bool f2fs_is_volatile_file(struct inode *inode) { return is_inode_flag_set(inode, FI_VOLATILE_FILE); } static inline bool f2fs_is_first_block_written(struct inode *inode) { return is_inode_flag_set(inode, FI_FIRST_BLOCK_WRITTEN); } static inline bool f2fs_is_drop_cache(struct inode *inode) { return is_inode_flag_set(inode, FI_DROP_CACHE); } static inline void *inline_data_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); int extra_size = get_extra_isize(inode); return (void *)&(ri->i_addr[extra_size + DEF_INLINE_RESERVED_SIZE]); } static inline int f2fs_has_inline_dentry(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DENTRY); } static inline int is_file(struct inode *inode, int type) { return F2FS_I(inode)->i_advise & type; } static inline void set_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise |= type; f2fs_mark_inode_dirty_sync(inode, true); } static inline void clear_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise &= ~type; f2fs_mark_inode_dirty_sync(inode, true); } static inline bool f2fs_skip_inode_update(struct inode *inode, int dsync) { bool ret; if (dsync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); ret = list_empty(&F2FS_I(inode)->gdirty_list); spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } if (!is_inode_flag_set(inode, FI_AUTO_RECOVER) || file_keep_isize(inode) || i_size_read(inode) & ~PAGE_MASK) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time, &inode->i_atime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 1, &inode->i_ctime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 2, &inode->i_mtime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 3, &F2FS_I(inode)->i_crtime)) return false; down_read(&F2FS_I(inode)->i_sem); ret = F2FS_I(inode)->last_disk_size == i_size_read(inode); up_read(&F2FS_I(inode)->i_sem); return ret; } static inline bool f2fs_readonly(struct super_block *sb) { return sb_rdonly(sb); } static inline bool f2fs_cp_error(struct f2fs_sb_info *sbi) { return is_set_ckpt_flags(sbi, CP_ERROR_FLAG); } static inline bool is_dot_dotdot(const struct qstr *str) { if (str->len == 1 && str->name[0] == '.') return true; if (str->len == 2 && str->name[0] == '.' && str->name[1] == '.') return true; return false; } static inline bool f2fs_may_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (!test_opt(sbi, EXTENT_CACHE) || is_inode_flag_set(inode, FI_NO_EXTENT)) return false; /* * for recovered files during mount do not create extents * if shrinker is not registered. */ if (list_empty(&sbi->s_list)) return false; return S_ISREG(inode->i_mode); } static inline void *f2fs_kmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { void *ret; if (time_to_inject(sbi, FAULT_KMALLOC)) { f2fs_show_injection_info(FAULT_KMALLOC); return NULL; } ret = kmalloc(size, flags); if (ret) return ret; return kvmalloc(size, flags); } static inline void *f2fs_kzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kmalloc(sbi, size, flags | __GFP_ZERO); } static inline void *f2fs_kvmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { if (time_to_inject(sbi, FAULT_KVMALLOC)) { f2fs_show_injection_info(FAULT_KVMALLOC); return NULL; } return kvmalloc(size, flags); } static inline void *f2fs_kvzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kvmalloc(sbi, size, flags | __GFP_ZERO); } static inline int get_extra_isize(struct inode *inode) { return F2FS_I(inode)->i_extra_isize / sizeof(__le32); } static inline int get_inline_xattr_addrs(struct inode *inode) { return F2FS_I(inode)->i_inline_xattr_size; } #define f2fs_get_inode_mode(i) \ ((is_inode_flag_set(i, FI_ACL_MODE)) ? \ (F2FS_I(i)->i_acl_mode) : ((i)->i_mode)) #define F2FS_TOTAL_EXTRA_ATTR_SIZE \ (offsetof(struct f2fs_inode, i_extra_end) - \ offsetof(struct f2fs_inode, i_extra_isize)) \ #define F2FS_OLD_ATTRIBUTE_SIZE (offsetof(struct f2fs_inode, i_addr)) #define F2FS_FITS_IN_INODE(f2fs_inode, extra_isize, field) \ ((offsetof(typeof(*(f2fs_inode)), field) + \ sizeof((f2fs_inode)->field)) \ <= (F2FS_OLD_ATTRIBUTE_SIZE + (extra_isize))) \ static inline void f2fs_reset_iostat(struct f2fs_sb_info *sbi) { int i; spin_lock(&sbi->iostat_lock); for (i = 0; i < NR_IO_TYPE; i++) sbi->write_iostat[i] = 0; spin_unlock(&sbi->iostat_lock); } static inline void f2fs_update_iostat(struct f2fs_sb_info *sbi, enum iostat_type type, unsigned long long io_bytes) { if (!sbi->iostat_enable) return; spin_lock(&sbi->iostat_lock); sbi->write_iostat[type] += io_bytes; if (type == APP_WRITE_IO || type == APP_DIRECT_IO) sbi->write_iostat[APP_BUFFERED_IO] = sbi->write_iostat[APP_WRITE_IO] - sbi->write_iostat[APP_DIRECT_IO]; spin_unlock(&sbi->iostat_lock); } #define __is_large_section(sbi) ((sbi)->segs_per_sec > 1) #define __is_meta_io(fio) (PAGE_TYPE_OF_BIO((fio)->type) == META) bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); static inline void verify_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type) { if (!f2fs_is_valid_blkaddr(sbi, blkaddr, type)) { f2fs_err(sbi, "invalid blkaddr: %u, type: %d, run fsck to fix.", blkaddr, type); f2fs_bug_on(sbi, 1); } } static inline bool __is_valid_data_blkaddr(block_t blkaddr) { if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR) return false; return true; } static inline void f2fs_set_page_private(struct page *page, unsigned long data) { if (PagePrivate(page)) return; get_page(page); SetPagePrivate(page); set_page_private(page, data); } static inline void f2fs_clear_page_private(struct page *page) { if (!PagePrivate(page)) return; set_page_private(page, 0); ClearPagePrivate(page); f2fs_put_page(page, 0); } /* * file.c */ int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync); void f2fs_truncate_data_blocks(struct dnode_of_data *dn); int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock); int f2fs_truncate(struct inode *inode); int f2fs_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int flags); int f2fs_setattr(struct dentry *dentry, struct iattr *attr); int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end); void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count); int f2fs_precache_extents(struct inode *inode); long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid); int f2fs_pin_file_control(struct inode *inode, bool inc); /* * inode.c */ void f2fs_set_inode_flags(struct inode *inode); bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct page *page); void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct page *page); struct inode *f2fs_iget(struct super_block *sb, unsigned long ino); struct inode *f2fs_iget_retry(struct super_block *sb, unsigned long ino); int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_update_inode(struct inode *inode, struct page *node_page); void f2fs_update_inode_page(struct inode *inode); int f2fs_write_inode(struct inode *inode, struct writeback_control *wbc); void f2fs_evict_inode(struct inode *inode); void f2fs_handle_failed_inode(struct inode *inode); /* * namei.c */ int f2fs_update_extension_list(struct f2fs_sb_info *sbi, const char *name, bool hot, bool set); struct dentry *f2fs_get_parent(struct dentry *child); /* * dir.c */ unsigned char f2fs_get_de_type(struct f2fs_dir_entry *de); struct f2fs_dir_entry *f2fs_find_target_dentry(struct fscrypt_name *fname, f2fs_hash_t namehash, int *max_slots, struct f2fs_dentry_ptr *d); int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d, unsigned int start_pos, struct fscrypt_str *fstr); void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent, struct f2fs_dentry_ptr *d); struct page *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct page *dpage); void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode, unsigned int current_depth); int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots); void f2fs_drop_nlink(struct inode *dir, struct inode *inode); struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir, const struct qstr *child, struct page **res_page); struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p); ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr, struct page **page); void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de, struct page *page, struct inode *inode); void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d, const struct qstr *name, f2fs_hash_t name_hash, unsigned int bit_pos); int f2fs_add_regular_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); int f2fs_add_dentry(struct inode *dir, struct fscrypt_name *fname, struct inode *inode, nid_t ino, umode_t mode); int f2fs_do_add_link(struct inode *dir, const struct qstr *name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); int f2fs_do_tmpfile(struct inode *inode, struct inode *dir); bool f2fs_empty_dir(struct inode *dir); static inline int f2fs_add_link(struct dentry *dentry, struct inode *inode) { return f2fs_do_add_link(d_inode(dentry->d_parent), &dentry->d_name, inode, inode->i_ino, inode->i_mode); } /* * super.c */ int f2fs_inode_dirtied(struct inode *inode, bool sync); void f2fs_inode_synced(struct inode *inode); int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly); int f2fs_quota_sync(struct super_block *sb, int type); void f2fs_quota_off_umount(struct super_block *sb); int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover); int f2fs_sync_fs(struct super_block *sb, int sync); int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi); /* * hash.c */ f2fs_hash_t f2fs_dentry_hash(const struct qstr *name_info, struct fscrypt_name *fname); /* * node.c */ struct dnode_of_data; struct node_info; int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type); bool f2fs_in_warm_node_list(struct f2fs_sb_info *sbi, struct page *page); void f2fs_init_fsync_node_info(struct f2fs_sb_info *sbi); void f2fs_del_fsync_node_entry(struct f2fs_sb_info *sbi, struct page *page); void f2fs_reset_fsync_node_info(struct f2fs_sb_info *sbi); int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid, struct node_info *ni); pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs); int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode); int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from); int f2fs_truncate_xattr_node(struct inode *inode); int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi, unsigned int seq_id); int f2fs_remove_inode_page(struct inode *inode); struct page *f2fs_new_inode_page(struct inode *inode); struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs); void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid); struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid); struct page *f2fs_get_node_page_ra(struct page *parent, int start); int f2fs_move_node_page(struct page *node_page, int gc_type); int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode, struct writeback_control *wbc, bool atomic, unsigned int *seq_id); int f2fs_sync_node_pages(struct f2fs_sb_info *sbi, struct writeback_control *wbc, bool do_balance, enum iostat_type io_type); int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount); bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid); void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid); void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid); int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_recover_inline_xattr(struct inode *inode, struct page *page); int f2fs_recover_xattr_data(struct inode *inode, struct page *page); int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page); int f2fs_restore_node_summary(struct f2fs_sb_info *sbi, unsigned int segno, struct f2fs_summary_block *sum); int f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_node_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_node_manager_caches(void); void f2fs_destroy_node_manager_caches(void); /* * segment.c */ bool f2fs_need_SSR(struct f2fs_sb_info *sbi); void f2fs_register_inmem_page(struct inode *inode, struct page *page); void f2fs_drop_inmem_pages_all(struct f2fs_sb_info *sbi, bool gc_failure); void f2fs_drop_inmem_pages(struct inode *inode); void f2fs_drop_inmem_page(struct inode *inode, struct page *page); int f2fs_commit_inmem_pages(struct inode *inode); void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need); void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi); int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi); int f2fs_flush_device_cache(struct f2fs_sb_info *sbi); void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free); void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr); bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi); void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi); bool f2fs_issue_discard_timeout(struct f2fs_sb_info *sbi); void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi); block_t f2fs_get_unusable_blocks(struct f2fs_sb_info *sbi); int f2fs_disable_cp_again(struct f2fs_sb_info *sbi, block_t unusable); void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi); int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra); void allocate_segment_for_resize(struct f2fs_sb_info *sbi, int type, unsigned int start, unsigned int end); void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi); int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range); bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc); struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno); void f2fs_update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr); void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page, enum iostat_type io_type); void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio); void f2fs_outplace_write_data(struct dnode_of_data *dn, struct f2fs_io_info *fio); int f2fs_inplace_write_data(struct f2fs_io_info *fio); void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum, block_t old_blkaddr, block_t new_blkaddr, bool recover_curseg, bool recover_newaddr); void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn, block_t old_addr, block_t new_addr, unsigned char version, bool recover_curseg, bool recover_newaddr); void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page, block_t old_blkaddr, block_t *new_blkaddr, struct f2fs_summary *sum, int type, struct f2fs_io_info *fio, bool add_list); void f2fs_wait_on_page_writeback(struct page *page, enum page_type type, bool ordered, bool locked); void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr); void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr, block_t len); void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk); void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk); int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type, unsigned int val, int alloc); void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_segment_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_segment_manager_caches(void); void f2fs_destroy_segment_manager_caches(void); int f2fs_rw_hint_to_seg_type(enum rw_hint hint); enum rw_hint f2fs_io_type_to_rw_hint(struct f2fs_sb_info *sbi, enum page_type type, enum temp_type temp); /* * checkpoint.c */ void f2fs_stop_checkpoint(struct f2fs_sb_info *sbi, bool end_io); struct page *f2fs_grab_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page_nofail(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_tmp_page(struct f2fs_sb_info *sbi, pgoff_t index); bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); int f2fs_ra_meta_pages(struct f2fs_sb_info *sbi, block_t start, int nrpages, int type, bool sync); void f2fs_ra_meta_pages_cond(struct f2fs_sb_info *sbi, pgoff_t index); long f2fs_sync_meta_pages(struct f2fs_sb_info *sbi, enum page_type type, long nr_to_write, enum iostat_type io_type); void f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all); bool f2fs_exist_written_data(struct f2fs_sb_info *sbi, nid_t ino, int mode); void f2fs_set_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); bool f2fs_is_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); int f2fs_sync_inode_meta(struct f2fs_sb_info *sbi); int f2fs_acquire_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_release_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_add_orphan_inode(struct inode *inode); void f2fs_remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_recover_orphan_inodes(struct f2fs_sb_info *sbi); int f2fs_get_valid_checkpoint(struct f2fs_sb_info *sbi); void f2fs_update_dirty_page(struct inode *inode, struct page *page); void f2fs_remove_dirty_inode(struct inode *inode); int f2fs_sync_dirty_inodes(struct f2fs_sb_info *sbi, enum inode_type type); void f2fs_wait_on_all_pages_writeback(struct f2fs_sb_info *sbi); int f2fs_write_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_init_ino_entry_info(struct f2fs_sb_info *sbi); int __init f2fs_create_checkpoint_caches(void); void f2fs_destroy_checkpoint_caches(void); /* * data.c */ int f2fs_init_post_read_processing(void); void f2fs_destroy_post_read_processing(void); void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type); void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, nid_t ino, enum page_type type); void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi); int f2fs_submit_page_bio(struct f2fs_io_info *fio); int f2fs_merge_page_bio(struct f2fs_io_info *fio); void f2fs_submit_page_write(struct f2fs_io_info *fio); struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi, block_t blk_addr, struct bio *bio); int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_set_data_blkaddr(struct dnode_of_data *dn); void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr); int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count); int f2fs_reserve_new_block(struct dnode_of_data *dn); int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index); int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from); int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index); struct page *f2fs_get_read_data_page(struct inode *inode, pgoff_t index, int op_flags, bool for_write); struct page *f2fs_find_data_page(struct inode *inode, pgoff_t index); struct page *f2fs_get_lock_data_page(struct inode *inode, pgoff_t index, bool for_write); struct page *f2fs_get_new_data_page(struct inode *inode, struct page *ipage, pgoff_t index, bool new_i_size); int f2fs_do_write_data_page(struct f2fs_io_info *fio); void __do_map_lock(struct f2fs_sb_info *sbi, int flag, bool lock); int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int create, int flag); int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len); bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio); bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio); void f2fs_invalidate_page(struct page *page, unsigned int offset, unsigned int length); int f2fs_release_page(struct page *page, gfp_t wait); #ifdef CONFIG_MIGRATION int f2fs_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode); #endif bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len); void f2fs_clear_page_cache_dirty_tag(struct page *page); /* * gc.c */ int f2fs_start_gc_thread(struct f2fs_sb_info *sbi); void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi); block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode); int f2fs_gc(struct f2fs_sb_info *sbi, bool sync, bool background, unsigned int segno); void f2fs_build_gc_manager(struct f2fs_sb_info *sbi); int f2fs_resize_fs(struct f2fs_sb_info *sbi, __u64 block_count); /* * recovery.c */ int f2fs_recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only); bool f2fs_space_for_roll_forward(struct f2fs_sb_info *sbi); /* * debug.c */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info { struct list_head stat_list; struct f2fs_sb_info *sbi; int all_area_segs, sit_area_segs, nat_area_segs, ssa_area_segs; int main_area_segs, main_area_sections, main_area_zones; unsigned long long hit_largest, hit_cached, hit_rbtree; unsigned long long hit_total, total_ext; int ext_tree, zombie_tree, ext_node; int ndirty_node, ndirty_dent, ndirty_meta, ndirty_imeta; int ndirty_data, ndirty_qdata; int inmem_pages; unsigned int ndirty_dirs, ndirty_files, nquota_files, ndirty_all; int nats, dirty_nats, sits, dirty_sits; int free_nids, avail_nids, alloc_nids; int total_count, utilization; int bg_gc, nr_wb_cp_data, nr_wb_data; int nr_rd_data, nr_rd_node, nr_rd_meta; int nr_dio_read, nr_dio_write; unsigned int io_skip_bggc, other_skip_bggc; int nr_flushing, nr_flushed, flush_list_empty; int nr_discarding, nr_discarded; int nr_discard_cmd; unsigned int undiscard_blks; int inline_xattr, inline_inode, inline_dir, append, update, orphans; int aw_cnt, max_aw_cnt, vw_cnt, max_vw_cnt; unsigned int valid_count, valid_node_count, valid_inode_count, discard_blks; unsigned int bimodal, avg_vblocks; int util_free, util_valid, util_invalid; int rsvd_segs, overp_segs; int dirty_count, node_pages, meta_pages; int prefree_count, call_count, cp_count, bg_cp_count; int tot_segs, node_segs, data_segs, free_segs, free_secs; int bg_node_segs, bg_data_segs; int tot_blks, data_blks, node_blks; int bg_data_blks, bg_node_blks; unsigned long long skipped_atomic_files[2]; int curseg[NR_CURSEG_TYPE]; int cursec[NR_CURSEG_TYPE]; int curzone[NR_CURSEG_TYPE]; unsigned int meta_count[META_MAX]; unsigned int segment_count[2]; unsigned int block_count[2]; unsigned int inplace_count; unsigned long long base_mem, cache_mem, page_mem; }; static inline struct f2fs_stat_info *F2FS_STAT(struct f2fs_sb_info *sbi) { return (struct f2fs_stat_info *)sbi->stat_info; } #define stat_inc_cp_count(si) ((si)->cp_count++) #define stat_inc_bg_cp_count(si) ((si)->bg_cp_count++) #define stat_inc_call_count(si) ((si)->call_count++) #define stat_inc_bggc_count(sbi) ((sbi)->bg_gc++) #define stat_io_skip_bggc_count(sbi) ((sbi)->io_skip_bggc++) #define stat_other_skip_bggc_count(sbi) ((sbi)->other_skip_bggc++) #define stat_inc_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]++) #define stat_dec_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]--) #define stat_inc_total_hit(sbi) (atomic64_inc(&(sbi)->total_hit_ext)) #define stat_inc_rbtree_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_rbtree)) #define stat_inc_largest_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_largest)) #define stat_inc_cached_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_cached)) #define stat_inc_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_dec_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_inc_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_dec_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_inc_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_dec_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_inc_meta_count(sbi, blkaddr) \ do { \ if (blkaddr < SIT_I(sbi)->sit_base_addr) \ atomic_inc(&(sbi)->meta_count[META_CP]); \ else if (blkaddr < NM_I(sbi)->nat_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SIT]); \ else if (blkaddr < SM_I(sbi)->ssa_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_NAT]); \ else if (blkaddr < SM_I(sbi)->main_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SSA]); \ } while (0) #define stat_inc_seg_type(sbi, curseg) \ ((sbi)->segment_count[(curseg)->alloc_type]++) #define stat_inc_block_count(sbi, curseg) \ ((sbi)->block_count[(curseg)->alloc_type]++) #define stat_inc_inplace_blocks(sbi) \ (atomic_inc(&(sbi)->inplace_count)) #define stat_inc_atomic_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->aw_cnt)) #define stat_dec_atomic_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->aw_cnt)) #define stat_update_max_atomic_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->aw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_aw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_aw_cnt, cur); \ } while (0) #define stat_inc_volatile_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->vw_cnt)) #define stat_dec_volatile_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->vw_cnt)) #define stat_update_max_volatile_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->vw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_vw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_vw_cnt, cur); \ } while (0) #define stat_inc_seg_count(sbi, type, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ si->tot_segs++; \ if ((type) == SUM_TYPE_DATA) { \ si->data_segs++; \ si->bg_data_segs += (gc_type == BG_GC) ? 1 : 0; \ } else { \ si->node_segs++; \ si->bg_node_segs += (gc_type == BG_GC) ? 1 : 0; \ } \ } while (0) #define stat_inc_tot_blk_count(si, blks) \ ((si)->tot_blks += (blks)) #define stat_inc_data_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->data_blks += (blks); \ si->bg_data_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->node_blks += (blks); \ si->bg_node_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) int f2fs_build_stats(struct f2fs_sb_info *sbi); void f2fs_destroy_stats(struct f2fs_sb_info *sbi); void __init f2fs_create_root_stats(void); void f2fs_destroy_root_stats(void); #else #define stat_inc_cp_count(si) do { } while (0) #define stat_inc_bg_cp_count(si) do { } while (0) #define stat_inc_call_count(si) do { } while (0) #define stat_inc_bggc_count(si) do { } while (0) #define stat_io_skip_bggc_count(sbi) do { } while (0) #define stat_other_skip_bggc_count(sbi) do { } while (0) #define stat_inc_dirty_inode(sbi, type) do { } while (0) #define stat_dec_dirty_inode(sbi, type) do { } while (0) #define stat_inc_total_hit(sb) do { } while (0) #define stat_inc_rbtree_node_hit(sb) do { } while (0) #define stat_inc_largest_node_hit(sbi) do { } while (0) #define stat_inc_cached_node_hit(sbi) do { } while (0) #define stat_inc_inline_xattr(inode) do { } while (0) #define stat_dec_inline_xattr(inode) do { } while (0) #define stat_inc_inline_inode(inode) do { } while (0) #define stat_dec_inline_inode(inode) do { } while (0) #define stat_inc_inline_dir(inode) do { } while (0) #define stat_dec_inline_dir(inode) do { } while (0) #define stat_inc_atomic_write(inode) do { } while (0) #define stat_dec_atomic_write(inode) do { } while (0) #define stat_update_max_atomic_write(inode) do { } while (0) #define stat_inc_volatile_write(inode) do { } while (0) #define stat_dec_volatile_write(inode) do { } while (0) #define stat_update_max_volatile_write(inode) do { } while (0) #define stat_inc_meta_count(sbi, blkaddr) do { } while (0) #define stat_inc_seg_type(sbi, curseg) do { } while (0) #define stat_inc_block_count(sbi, curseg) do { } while (0) #define stat_inc_inplace_blocks(sbi) do { } while (0) #define stat_inc_seg_count(sbi, type, gc_type) do { } while (0) #define stat_inc_tot_blk_count(si, blks) do { } while (0) #define stat_inc_data_blk_count(sbi, blks, gc_type) do { } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) do { } while (0) static inline int f2fs_build_stats(struct f2fs_sb_info *sbi) { return 0; } static inline void f2fs_destroy_stats(struct f2fs_sb_info *sbi) { } static inline void __init f2fs_create_root_stats(void) { } static inline void f2fs_destroy_root_stats(void) { } #endif extern const struct file_operations f2fs_dir_operations; extern const struct file_operations f2fs_file_operations; extern const struct inode_operations f2fs_file_inode_operations; extern const struct address_space_operations f2fs_dblock_aops; extern const struct address_space_operations f2fs_node_aops; extern const struct address_space_operations f2fs_meta_aops; extern const struct inode_operations f2fs_dir_inode_operations; extern const struct inode_operations f2fs_symlink_inode_operations; extern const struct inode_operations f2fs_encrypted_symlink_inode_operations; extern const struct inode_operations f2fs_special_inode_operations; extern struct kmem_cache *f2fs_inode_entry_slab; /* * inline.c */ bool f2fs_may_inline_data(struct inode *inode); bool f2fs_may_inline_dentry(struct inode *inode); void f2fs_do_read_inline_data(struct page *page, struct page *ipage); void f2fs_truncate_inline_inode(struct inode *inode, struct page *ipage, u64 from); int f2fs_read_inline_data(struct inode *inode, struct page *page); int f2fs_convert_inline_page(struct dnode_of_data *dn, struct page *page); int f2fs_convert_inline_inode(struct inode *inode); int f2fs_write_inline_data(struct inode *inode, struct page *page); bool f2fs_recover_inline_data(struct inode *inode, struct page *npage); struct f2fs_dir_entry *f2fs_find_in_inline_dir(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); int f2fs_make_empty_inline_dir(struct inode *inode, struct inode *parent, struct page *ipage); int f2fs_add_inline_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_inline_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); bool f2fs_empty_inline_dir(struct inode *dir); int f2fs_read_inline_dir(struct file *file, struct dir_context *ctx, struct fscrypt_str *fstr); int f2fs_inline_data_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len); /* * shrinker.c */ unsigned long f2fs_shrink_count(struct shrinker *shrink, struct shrink_control *sc); unsigned long f2fs_shrink_scan(struct shrinker *shrink, struct shrink_control *sc); void f2fs_join_shrinker(struct f2fs_sb_info *sbi); void f2fs_leave_shrinker(struct f2fs_sb_info *sbi); /* * extent_cache.c */ struct rb_entry *f2fs_lookup_rb_tree(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs); struct rb_node **f2fs_lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi, struct rb_root_cached *root, struct rb_node **parent, unsigned int ofs, bool *leftmost); struct rb_entry *f2fs_lookup_rb_tree_ret(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs, struct rb_entry **prev_entry, struct rb_entry **next_entry, struct rb_node ***insert_p, struct rb_node **insert_parent, bool force, bool *leftmost); bool f2fs_check_rb_tree_consistence(struct f2fs_sb_info *sbi, struct rb_root_cached *root); unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink); bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext); void f2fs_drop_extent_tree(struct inode *inode); unsigned int f2fs_destroy_extent_node(struct inode *inode); void f2fs_destroy_extent_tree(struct inode *inode); bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs, struct extent_info *ei); void f2fs_update_extent_cache(struct dnode_of_data *dn); void f2fs_update_extent_cache_range(struct dnode_of_data *dn, pgoff_t fofs, block_t blkaddr, unsigned int len); void f2fs_init_extent_cache_info(struct f2fs_sb_info *sbi); int __init f2fs_create_extent_cache(void); void f2fs_destroy_extent_cache(void); /* * sysfs.c */ int __init f2fs_init_sysfs(void); void f2fs_exit_sysfs(void); int f2fs_register_sysfs(struct f2fs_sb_info *sbi); void f2fs_unregister_sysfs(struct f2fs_sb_info *sbi); /* * crypto support */ static inline bool f2fs_encrypted_file(struct inode *inode) { return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode); } static inline void f2fs_set_encrypted_inode(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION file_set_encrypt(inode); f2fs_set_inode_flags(inode); #endif } /* * Returns true if the reads of the inode's data need to undergo some * postprocessing step, like decryption or authenticity verification. */ static inline bool f2fs_post_read_required(struct inode *inode) { return f2fs_encrypted_file(inode); } #define F2FS_FEATURE_FUNCS(name, flagname) \ static inline int f2fs_sb_has_##name(struct f2fs_sb_info *sbi) \ { \ return F2FS_HAS_FEATURE(sbi, F2FS_FEATURE_##flagname); \ } F2FS_FEATURE_FUNCS(encrypt, ENCRYPT); F2FS_FEATURE_FUNCS(blkzoned, BLKZONED); F2FS_FEATURE_FUNCS(extra_attr, EXTRA_ATTR); F2FS_FEATURE_FUNCS(project_quota, PRJQUOTA); F2FS_FEATURE_FUNCS(inode_chksum, INODE_CHKSUM); F2FS_FEATURE_FUNCS(flexible_inline_xattr, FLEXIBLE_INLINE_XATTR); F2FS_FEATURE_FUNCS(quota_ino, QUOTA_INO); F2FS_FEATURE_FUNCS(inode_crtime, INODE_CRTIME); F2FS_FEATURE_FUNCS(lost_found, LOST_FOUND); F2FS_FEATURE_FUNCS(sb_chksum, SB_CHKSUM); #ifdef CONFIG_BLK_DEV_ZONED static inline bool f2fs_blkz_is_seq(struct f2fs_sb_info *sbi, int devi, block_t blkaddr) { unsigned int zno = blkaddr >> sbi->log_blocks_per_blkz; return test_bit(zno, FDEV(devi).blkz_seq); } #endif static inline bool f2fs_hw_should_discard(struct f2fs_sb_info *sbi) { return f2fs_sb_has_blkzoned(sbi); } static inline bool f2fs_bdev_support_discard(struct block_device *bdev) { return blk_queue_discard(bdev_get_queue(bdev)) || bdev_is_zoned(bdev); } static inline bool f2fs_hw_support_discard(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return f2fs_bdev_support_discard(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (f2fs_bdev_support_discard(FDEV(i).bdev)) return true; return false; } static inline bool f2fs_realtime_discard_enable(struct f2fs_sb_info *sbi) { return (test_opt(sbi, DISCARD) && f2fs_hw_support_discard(sbi)) || f2fs_hw_should_discard(sbi); } static inline bool f2fs_hw_is_readonly(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return bdev_read_only(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (bdev_read_only(FDEV(i).bdev)) return true; return false; } static inline void set_opt_mode(struct f2fs_sb_info *sbi, unsigned int mt) { clear_opt(sbi, ADAPTIVE); clear_opt(sbi, LFS); switch (mt) { case F2FS_MOUNT_ADAPTIVE: set_opt(sbi, ADAPTIVE); break; case F2FS_MOUNT_LFS: set_opt(sbi, LFS); break; } } static inline bool f2fs_may_encrypt(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION umode_t mode = inode->i_mode; return (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)); #else return false; #endif } static inline int block_unaligned_IO(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { unsigned int i_blkbits = READ_ONCE(inode->i_blkbits); unsigned int blocksize_mask = (1 << i_blkbits) - 1; loff_t offset = iocb->ki_pos; unsigned long align = offset | iov_iter_alignment(iter); return align & blocksize_mask; } static inline int allow_outplace_dio(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); return (test_opt(sbi, LFS) && (rw == WRITE) && !block_unaligned_IO(inode, iocb, iter)); } static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED) && !(inode->i_flags & S_SWAPFILE)) return true; return false; } #ifdef CONFIG_F2FS_FAULT_INJECTION extern void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate, unsigned int type); #else #define f2fs_build_fault_attr(sbi, rate, type) do { } while (0) #endif static inline bool is_journalled_quota(struct f2fs_sb_info *sbi) { #ifdef CONFIG_QUOTA if (f2fs_sb_has_quota_ino(sbi)) return true; if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] || F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] || F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) return true; #endif return false; } #define EFSBADCRC EBADMSG /* Bad CRC detected */ #define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */ #endif /* _LINUX_F2FS_H */
static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page->mapping); }
static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page_file_mapping(page)); }
{'added': [(1501, '\treturn F2FS_M_SB(page_file_mapping(page));'), (3686, '\tif (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED) &&'), (3687, '\t\t\t\t\t!(inode->i_flags & S_SWAPFILE))')], 'deleted': [(1501, '\treturn F2FS_M_SB(page->mapping);'), (3686, '\tif (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED))')]}
3
2
2,531
14,991
https://github.com/torvalds/linux
CVE-2019-19815
['CWE-476']
f2fs.h
f2fs_force_buffered_io
// SPDX-License-Identifier: GPL-2.0 /* * fs/f2fs/f2fs.h * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ */ #ifndef _LINUX_F2FS_H #define _LINUX_F2FS_H #include <linux/uio.h> #include <linux/types.h> #include <linux/page-flags.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/crc32.h> #include <linux/magic.h> #include <linux/kobject.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/vmalloc.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/quotaops.h> #include <crypto/hash.h> #include <linux/fscrypt.h> #ifdef CONFIG_F2FS_CHECK_FS #define f2fs_bug_on(sbi, condition) BUG_ON(condition) #else #define f2fs_bug_on(sbi, condition) \ do { \ if (unlikely(condition)) { \ WARN_ON(1); \ set_sbi_flag(sbi, SBI_NEED_FSCK); \ } \ } while (0) #endif enum { FAULT_KMALLOC, FAULT_KVMALLOC, FAULT_PAGE_ALLOC, FAULT_PAGE_GET, FAULT_ALLOC_BIO, FAULT_ALLOC_NID, FAULT_ORPHAN, FAULT_BLOCK, FAULT_DIR_DEPTH, FAULT_EVICT_INODE, FAULT_TRUNCATE, FAULT_READ_IO, FAULT_CHECKPOINT, FAULT_DISCARD, FAULT_WRITE_IO, FAULT_MAX, }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define F2FS_ALL_FAULT_TYPE ((1 << FAULT_MAX) - 1) struct f2fs_fault_info { atomic_t inject_ops; unsigned int inject_rate; unsigned int inject_type; }; extern const char *f2fs_fault_name[FAULT_MAX]; #define IS_FAULT_SET(fi, type) ((fi)->inject_type & (1 << (type))) #endif /* * For mount options */ #define F2FS_MOUNT_BG_GC 0x00000001 #define F2FS_MOUNT_DISABLE_ROLL_FORWARD 0x00000002 #define F2FS_MOUNT_DISCARD 0x00000004 #define F2FS_MOUNT_NOHEAP 0x00000008 #define F2FS_MOUNT_XATTR_USER 0x00000010 #define F2FS_MOUNT_POSIX_ACL 0x00000020 #define F2FS_MOUNT_DISABLE_EXT_IDENTIFY 0x00000040 #define F2FS_MOUNT_INLINE_XATTR 0x00000080 #define F2FS_MOUNT_INLINE_DATA 0x00000100 #define F2FS_MOUNT_INLINE_DENTRY 0x00000200 #define F2FS_MOUNT_FLUSH_MERGE 0x00000400 #define F2FS_MOUNT_NOBARRIER 0x00000800 #define F2FS_MOUNT_FASTBOOT 0x00001000 #define F2FS_MOUNT_EXTENT_CACHE 0x00002000 #define F2FS_MOUNT_FORCE_FG_GC 0x00004000 #define F2FS_MOUNT_DATA_FLUSH 0x00008000 #define F2FS_MOUNT_FAULT_INJECTION 0x00010000 #define F2FS_MOUNT_ADAPTIVE 0x00020000 #define F2FS_MOUNT_LFS 0x00040000 #define F2FS_MOUNT_USRQUOTA 0x00080000 #define F2FS_MOUNT_GRPQUOTA 0x00100000 #define F2FS_MOUNT_PRJQUOTA 0x00200000 #define F2FS_MOUNT_QUOTA 0x00400000 #define F2FS_MOUNT_INLINE_XATTR_SIZE 0x00800000 #define F2FS_MOUNT_RESERVE_ROOT 0x01000000 #define F2FS_MOUNT_DISABLE_CHECKPOINT 0x02000000 #define F2FS_OPTION(sbi) ((sbi)->mount_opt) #define clear_opt(sbi, option) (F2FS_OPTION(sbi).opt &= ~F2FS_MOUNT_##option) #define set_opt(sbi, option) (F2FS_OPTION(sbi).opt |= F2FS_MOUNT_##option) #define test_opt(sbi, option) (F2FS_OPTION(sbi).opt & F2FS_MOUNT_##option) #define ver_after(a, b) (typecheck(unsigned long long, a) && \ typecheck(unsigned long long, b) && \ ((long long)((a) - (b)) > 0)) typedef u32 block_t; /* * should not change u32, since it is the on-disk block * address format, __le32. */ typedef u32 nid_t; struct f2fs_mount_info { unsigned int opt; int write_io_size_bits; /* Write IO size bits */ block_t root_reserved_blocks; /* root reserved blocks */ kuid_t s_resuid; /* reserved blocks for uid */ kgid_t s_resgid; /* reserved blocks for gid */ int active_logs; /* # of active logs */ int inline_xattr_size; /* inline xattr size */ #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info fault_info; /* For fault injection */ #endif #ifdef CONFIG_QUOTA /* Names of quota files with journalled quota */ char *s_qf_names[MAXQUOTAS]; int s_jquota_fmt; /* Format of quota to use */ #endif /* For which write hints are passed down to block layer */ int whint_mode; int alloc_mode; /* segment allocation policy */ int fsync_mode; /* fsync policy */ bool test_dummy_encryption; /* test dummy encryption */ block_t unusable_cap; /* Amount of space allowed to be * unusable when disabling checkpoint */ }; #define F2FS_FEATURE_ENCRYPT 0x0001 #define F2FS_FEATURE_BLKZONED 0x0002 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004 #define F2FS_FEATURE_EXTRA_ATTR 0x0008 #define F2FS_FEATURE_PRJQUOTA 0x0010 #define F2FS_FEATURE_INODE_CHKSUM 0x0020 #define F2FS_FEATURE_FLEXIBLE_INLINE_XATTR 0x0040 #define F2FS_FEATURE_QUOTA_INO 0x0080 #define F2FS_FEATURE_INODE_CRTIME 0x0100 #define F2FS_FEATURE_LOST_FOUND 0x0200 #define F2FS_FEATURE_VERITY 0x0400 /* reserved */ #define F2FS_FEATURE_SB_CHKSUM 0x0800 #define __F2FS_HAS_FEATURE(raw_super, mask) \ ((raw_super->feature & cpu_to_le32(mask)) != 0) #define F2FS_HAS_FEATURE(sbi, mask) __F2FS_HAS_FEATURE(sbi->raw_super, mask) #define F2FS_SET_FEATURE(sbi, mask) \ (sbi->raw_super->feature |= cpu_to_le32(mask)) #define F2FS_CLEAR_FEATURE(sbi, mask) \ (sbi->raw_super->feature &= ~cpu_to_le32(mask)) /* * Default values for user and/or group using reserved blocks */ #define F2FS_DEF_RESUID 0 #define F2FS_DEF_RESGID 0 /* * For checkpoint manager */ enum { NAT_BITMAP, SIT_BITMAP }; #define CP_UMOUNT 0x00000001 #define CP_FASTBOOT 0x00000002 #define CP_SYNC 0x00000004 #define CP_RECOVERY 0x00000008 #define CP_DISCARD 0x00000010 #define CP_TRIMMED 0x00000020 #define CP_PAUSE 0x00000040 #define MAX_DISCARD_BLOCKS(sbi) BLKS_PER_SEC(sbi) #define DEF_MAX_DISCARD_REQUEST 8 /* issue 8 discards per round */ #define DEF_MIN_DISCARD_ISSUE_TIME 50 /* 50 ms, if exists */ #define DEF_MID_DISCARD_ISSUE_TIME 500 /* 500 ms, if device busy */ #define DEF_MAX_DISCARD_ISSUE_TIME 60000 /* 60 s, if no candidates */ #define DEF_DISCARD_URGENT_UTIL 80 /* do more discard over 80% */ #define DEF_CP_INTERVAL 60 /* 60 secs */ #define DEF_IDLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_QUICK_INTERVAL 1 /* 1 secs */ #define DEF_UMOUNT_DISCARD_TIMEOUT 5 /* 5 secs */ struct cp_control { int reason; __u64 trim_start; __u64 trim_end; __u64 trim_minlen; }; /* * indicate meta/data type */ enum { META_CP, META_NAT, META_SIT, META_SSA, META_MAX, META_POR, DATA_GENERIC, /* check range only */ DATA_GENERIC_ENHANCE, /* strong check on range and segment bitmap */ DATA_GENERIC_ENHANCE_READ, /* * strong check on range and segment * bitmap but no warning due to race * condition of read on truncated area * by extent_cache */ META_GENERIC, }; /* for the list of ino */ enum { ORPHAN_INO, /* for orphan ino list */ APPEND_INO, /* for append ino list */ UPDATE_INO, /* for update ino list */ TRANS_DIR_INO, /* for trasactions dir ino list */ FLUSH_INO, /* for multiple device flushing */ MAX_INO_ENTRY, /* max. list */ }; struct ino_entry { struct list_head list; /* list head */ nid_t ino; /* inode number */ unsigned int dirty_device; /* dirty device bitmap */ }; /* for the list of inodes to be GCed */ struct inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ }; struct fsync_node_entry { struct list_head list; /* list head */ struct page *page; /* warm node page pointer */ unsigned int seq_id; /* sequence id */ }; /* for the bitmap indicate blocks to be discarded */ struct discard_entry { struct list_head list; /* list head */ block_t start_blkaddr; /* start blockaddr of current segment */ unsigned char discard_map[SIT_VBLOCK_MAP_SIZE]; /* segment discard bitmap */ }; /* default discard granularity of inner discard thread, unit: block count */ #define DEFAULT_DISCARD_GRANULARITY 16 /* max discard pend list number */ #define MAX_PLIST_NUM 512 #define plist_idx(blk_num) ((blk_num) >= MAX_PLIST_NUM ? \ (MAX_PLIST_NUM - 1) : ((blk_num) - 1)) enum { D_PREP, /* initial */ D_PARTIAL, /* partially submitted */ D_SUBMIT, /* all submitted */ D_DONE, /* finished */ }; struct discard_info { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_cmd { struct rb_node rb_node; /* rb node located in rb-tree */ union { struct { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_info di; /* discard info */ }; struct list_head list; /* command list */ struct completion wait; /* compleation */ struct block_device *bdev; /* bdev */ unsigned short ref; /* reference count */ unsigned char state; /* state */ unsigned char queued; /* queued discard */ int error; /* bio error */ spinlock_t lock; /* for state/bio_ref updating */ unsigned short bio_ref; /* bio reference count */ }; enum { DPOLICY_BG, DPOLICY_FORCE, DPOLICY_FSTRIM, DPOLICY_UMOUNT, MAX_DPOLICY, }; struct discard_policy { int type; /* type of discard */ unsigned int min_interval; /* used for candidates exist */ unsigned int mid_interval; /* used for device busy */ unsigned int max_interval; /* used for candidates not exist */ unsigned int max_requests; /* # of discards issued per round */ unsigned int io_aware_gran; /* minimum granularity discard not be aware of I/O */ bool io_aware; /* issue discard in idle time */ bool sync; /* submit discard with REQ_SYNC flag */ bool ordered; /* issue discard by lba order */ unsigned int granularity; /* discard granularity */ int timeout; /* discard timeout for put_super */ }; struct discard_cmd_control { struct task_struct *f2fs_issue_discard; /* discard thread */ struct list_head entry_list; /* 4KB discard entry list */ struct list_head pend_list[MAX_PLIST_NUM];/* store pending entries */ struct list_head wait_list; /* store on-flushing entries */ struct list_head fstrim_list; /* in-flight discard from fstrim */ wait_queue_head_t discard_wait_queue; /* waiting queue for wake-up */ unsigned int discard_wake; /* to wake up discard thread */ struct mutex cmd_lock; unsigned int nr_discards; /* # of discards in the list */ unsigned int max_discards; /* max. discards to be issued */ unsigned int discard_granularity; /* discard granularity */ unsigned int undiscard_blks; /* # of undiscard blocks */ unsigned int next_pos; /* next discard position */ atomic_t issued_discard; /* # of issued discard */ atomic_t queued_discard; /* # of queued discard */ atomic_t discard_cmd_cnt; /* # of cached cmd count */ struct rb_root_cached root; /* root of discard rb-tree */ bool rbtree_check; /* config for consistence check */ }; /* for the list of fsync inodes, used only during recovery */ struct fsync_inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ block_t blkaddr; /* block address locating the last fsync */ block_t last_dentry; /* block address locating the last dentry */ }; #define nats_in_cursum(jnl) (le16_to_cpu((jnl)->n_nats)) #define sits_in_cursum(jnl) (le16_to_cpu((jnl)->n_sits)) #define nat_in_journal(jnl, i) ((jnl)->nat_j.entries[i].ne) #define nid_in_journal(jnl, i) ((jnl)->nat_j.entries[i].nid) #define sit_in_journal(jnl, i) ((jnl)->sit_j.entries[i].se) #define segno_in_journal(jnl, i) ((jnl)->sit_j.entries[i].segno) #define MAX_NAT_JENTRIES(jnl) (NAT_JOURNAL_ENTRIES - nats_in_cursum(jnl)) #define MAX_SIT_JENTRIES(jnl) (SIT_JOURNAL_ENTRIES - sits_in_cursum(jnl)) static inline int update_nats_in_cursum(struct f2fs_journal *journal, int i) { int before = nats_in_cursum(journal); journal->n_nats = cpu_to_le16(before + i); return before; } static inline int update_sits_in_cursum(struct f2fs_journal *journal, int i) { int before = sits_in_cursum(journal); journal->n_sits = cpu_to_le16(before + i); return before; } static inline bool __has_cursum_space(struct f2fs_journal *journal, int size, int type) { if (type == NAT_JOURNAL) return size <= MAX_NAT_JENTRIES(journal); return size <= MAX_SIT_JENTRIES(journal); } /* * ioctl commands */ #define F2FS_IOC_GETFLAGS FS_IOC_GETFLAGS #define F2FS_IOC_SETFLAGS FS_IOC_SETFLAGS #define F2FS_IOC_GETVERSION FS_IOC_GETVERSION #define F2FS_IOCTL_MAGIC 0xf5 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) #define F2FS_IOC_RELEASE_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 4) #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) #define F2FS_IOC_GARBAGE_COLLECT _IOW(F2FS_IOCTL_MAGIC, 6, __u32) #define F2FS_IOC_WRITE_CHECKPOINT _IO(F2FS_IOCTL_MAGIC, 7) #define F2FS_IOC_DEFRAGMENT _IOWR(F2FS_IOCTL_MAGIC, 8, \ struct f2fs_defragment) #define F2FS_IOC_MOVE_RANGE _IOWR(F2FS_IOCTL_MAGIC, 9, \ struct f2fs_move_range) #define F2FS_IOC_FLUSH_DEVICE _IOW(F2FS_IOCTL_MAGIC, 10, \ struct f2fs_flush_device) #define F2FS_IOC_GARBAGE_COLLECT_RANGE _IOW(F2FS_IOCTL_MAGIC, 11, \ struct f2fs_gc_range) #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, __u32) #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) #define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) #define F2FS_IOC_PRECACHE_EXTENTS _IO(F2FS_IOCTL_MAGIC, 15) #define F2FS_IOC_RESIZE_FS _IOW(F2FS_IOCTL_MAGIC, 16, __u64) #define F2FS_IOC_SET_ENCRYPTION_POLICY FS_IOC_SET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_POLICY FS_IOC_GET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_PWSALT FS_IOC_GET_ENCRYPTION_PWSALT /* * should be same as XFS_IOC_GOINGDOWN. * Flags for going down operation used by FS_IOC_GOINGDOWN */ #define F2FS_IOC_SHUTDOWN _IOR('X', 125, __u32) /* Shutdown */ #define F2FS_GOING_DOWN_FULLSYNC 0x0 /* going down with full sync */ #define F2FS_GOING_DOWN_METASYNC 0x1 /* going down with metadata */ #define F2FS_GOING_DOWN_NOSYNC 0x2 /* going down */ #define F2FS_GOING_DOWN_METAFLUSH 0x3 /* going down with meta flush */ #define F2FS_GOING_DOWN_NEED_FSCK 0x4 /* going down to trigger fsck */ #if defined(__KERNEL__) && defined(CONFIG_COMPAT) /* * ioctl commands in 32 bit emulation */ #define F2FS_IOC32_GETFLAGS FS_IOC32_GETFLAGS #define F2FS_IOC32_SETFLAGS FS_IOC32_SETFLAGS #define F2FS_IOC32_GETVERSION FS_IOC32_GETVERSION #endif #define F2FS_IOC_FSGETXATTR FS_IOC_FSGETXATTR #define F2FS_IOC_FSSETXATTR FS_IOC_FSSETXATTR struct f2fs_gc_range { u32 sync; u64 start; u64 len; }; struct f2fs_defragment { u64 start; u64 len; }; struct f2fs_move_range { u32 dst_fd; /* destination fd */ u64 pos_in; /* start position in src_fd */ u64 pos_out; /* start position in dst_fd */ u64 len; /* size to move */ }; struct f2fs_flush_device { u32 dev_num; /* device number to flush */ u32 segments; /* # of segments to flush */ }; /* for inline stuff */ #define DEF_INLINE_RESERVED_SIZE 1 static inline int get_extra_isize(struct inode *inode); static inline int get_inline_xattr_addrs(struct inode *inode); #define MAX_INLINE_DATA(inode) (sizeof(__le32) * \ (CUR_ADDRS_PER_INODE(inode) - \ get_inline_xattr_addrs(inode) - \ DEF_INLINE_RESERVED_SIZE)) /* for inline dir */ #define NR_INLINE_DENTRY(inode) (MAX_INLINE_DATA(inode) * BITS_PER_BYTE / \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ BITS_PER_BYTE + 1)) #define INLINE_DENTRY_BITMAP_SIZE(inode) \ DIV_ROUND_UP(NR_INLINE_DENTRY(inode), BITS_PER_BYTE) #define INLINE_RESERVED_SIZE(inode) (MAX_INLINE_DATA(inode) - \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ NR_INLINE_DENTRY(inode) + \ INLINE_DENTRY_BITMAP_SIZE(inode))) /* * For INODE and NODE manager */ /* for directory operations */ struct f2fs_dentry_ptr { struct inode *inode; void *bitmap; struct f2fs_dir_entry *dentry; __u8 (*filename)[F2FS_SLOT_LEN]; int max; int nr_bitmap; }; static inline void make_dentry_ptr_block(struct inode *inode, struct f2fs_dentry_ptr *d, struct f2fs_dentry_block *t) { d->inode = inode; d->max = NR_DENTRY_IN_BLOCK; d->nr_bitmap = SIZE_OF_DENTRY_BITMAP; d->bitmap = t->dentry_bitmap; d->dentry = t->dentry; d->filename = t->filename; } static inline void make_dentry_ptr_inline(struct inode *inode, struct f2fs_dentry_ptr *d, void *t) { int entry_cnt = NR_INLINE_DENTRY(inode); int bitmap_size = INLINE_DENTRY_BITMAP_SIZE(inode); int reserved_size = INLINE_RESERVED_SIZE(inode); d->inode = inode; d->max = entry_cnt; d->nr_bitmap = bitmap_size; d->bitmap = t; d->dentry = t + bitmap_size + reserved_size; d->filename = t + bitmap_size + reserved_size + SIZE_OF_DIR_ENTRY * entry_cnt; } /* * XATTR_NODE_OFFSET stores xattrs to one node block per file keeping -1 * as its node offset to distinguish from index node blocks. * But some bits are used to mark the node block. */ #define XATTR_NODE_OFFSET ((((unsigned int)-1) << OFFSET_BIT_SHIFT) \ >> OFFSET_BIT_SHIFT) enum { ALLOC_NODE, /* allocate a new node page if needed */ LOOKUP_NODE, /* look up a node without readahead */ LOOKUP_NODE_RA, /* * look up a node with readahead called * by get_data_block. */ }; #define DEFAULT_RETRY_IO_COUNT 8 /* maximum retry read IO count */ /* maximum retry quota flush count */ #define DEFAULT_RETRY_QUOTA_FLUSH_COUNT 8 #define F2FS_LINK_MAX 0xffffffff /* maximum link count per file */ #define MAX_DIR_RA_PAGES 4 /* maximum ra pages of dir */ /* for in-memory extent cache entry */ #define F2FS_MIN_EXTENT_LEN 64 /* minimum extent length */ /* number of extent info in extent cache we try to shrink */ #define EXTENT_CACHE_SHRINK_NUMBER 128 struct rb_entry { struct rb_node rb_node; /* rb node located in rb-tree */ unsigned int ofs; /* start offset of the entry */ unsigned int len; /* length of the entry */ }; struct extent_info { unsigned int fofs; /* start offset in a file */ unsigned int len; /* length of the extent */ u32 blk; /* start block address of the extent */ }; struct extent_node { struct rb_node rb_node; /* rb node located in rb-tree */ struct extent_info ei; /* extent info */ struct list_head list; /* node in global extent list of sbi */ struct extent_tree *et; /* extent tree pointer */ }; struct extent_tree { nid_t ino; /* inode number */ struct rb_root_cached root; /* root of extent info rb-tree */ struct extent_node *cached_en; /* recently accessed extent node */ struct extent_info largest; /* largested extent info */ struct list_head list; /* to be used by sbi->zombie_list */ rwlock_t lock; /* protect extent info rb-tree */ atomic_t node_cnt; /* # of extent node in rb-tree*/ bool largest_updated; /* largest extent updated */ }; /* * This structure is taken from ext4_map_blocks. * * Note that, however, f2fs uses NEW and MAPPED flags for f2fs_map_blocks(). */ #define F2FS_MAP_NEW (1 << BH_New) #define F2FS_MAP_MAPPED (1 << BH_Mapped) #define F2FS_MAP_UNWRITTEN (1 << BH_Unwritten) #define F2FS_MAP_FLAGS (F2FS_MAP_NEW | F2FS_MAP_MAPPED |\ F2FS_MAP_UNWRITTEN) struct f2fs_map_blocks { block_t m_pblk; block_t m_lblk; unsigned int m_len; unsigned int m_flags; pgoff_t *m_next_pgofs; /* point next possible non-hole pgofs */ pgoff_t *m_next_extent; /* point to next possible extent */ int m_seg_type; bool m_may_create; /* indicate it is from write path */ }; /* for flag in get_data_block */ enum { F2FS_GET_BLOCK_DEFAULT, F2FS_GET_BLOCK_FIEMAP, F2FS_GET_BLOCK_BMAP, F2FS_GET_BLOCK_DIO, F2FS_GET_BLOCK_PRE_DIO, F2FS_GET_BLOCK_PRE_AIO, F2FS_GET_BLOCK_PRECACHE, }; /* * i_advise uses FADVISE_XXX_BIT. We can add additional hints later. */ #define FADVISE_COLD_BIT 0x01 #define FADVISE_LOST_PINO_BIT 0x02 #define FADVISE_ENCRYPT_BIT 0x04 #define FADVISE_ENC_NAME_BIT 0x08 #define FADVISE_KEEP_SIZE_BIT 0x10 #define FADVISE_HOT_BIT 0x20 #define FADVISE_VERITY_BIT 0x40 /* reserved */ #define FADVISE_MODIFIABLE_BITS (FADVISE_COLD_BIT | FADVISE_HOT_BIT) #define file_is_cold(inode) is_file(inode, FADVISE_COLD_BIT) #define file_wrong_pino(inode) is_file(inode, FADVISE_LOST_PINO_BIT) #define file_set_cold(inode) set_file(inode, FADVISE_COLD_BIT) #define file_lost_pino(inode) set_file(inode, FADVISE_LOST_PINO_BIT) #define file_clear_cold(inode) clear_file(inode, FADVISE_COLD_BIT) #define file_got_pino(inode) clear_file(inode, FADVISE_LOST_PINO_BIT) #define file_is_encrypt(inode) is_file(inode, FADVISE_ENCRYPT_BIT) #define file_set_encrypt(inode) set_file(inode, FADVISE_ENCRYPT_BIT) #define file_clear_encrypt(inode) clear_file(inode, FADVISE_ENCRYPT_BIT) #define file_enc_name(inode) is_file(inode, FADVISE_ENC_NAME_BIT) #define file_set_enc_name(inode) set_file(inode, FADVISE_ENC_NAME_BIT) #define file_keep_isize(inode) is_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_set_keep_isize(inode) set_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_is_hot(inode) is_file(inode, FADVISE_HOT_BIT) #define file_set_hot(inode) set_file(inode, FADVISE_HOT_BIT) #define file_clear_hot(inode) clear_file(inode, FADVISE_HOT_BIT) #define DEF_DIR_LEVEL 0 enum { GC_FAILURE_PIN, GC_FAILURE_ATOMIC, MAX_GC_FAILURE }; struct f2fs_inode_info { struct inode vfs_inode; /* serve a vfs inode */ unsigned long i_flags; /* keep an inode flags for ioctl */ unsigned char i_advise; /* use to give file attribute hints */ unsigned char i_dir_level; /* use for dentry level for large dir */ unsigned int i_current_depth; /* only for directory depth */ /* for gc failure statistic */ unsigned int i_gc_failures[MAX_GC_FAILURE]; unsigned int i_pino; /* parent inode number */ umode_t i_acl_mode; /* keep file acl mode temporarily */ /* Use below internally in f2fs*/ unsigned long flags; /* use to pass per-file flags */ struct rw_semaphore i_sem; /* protect fi info */ atomic_t dirty_pages; /* # of dirty pages */ f2fs_hash_t chash; /* hash value of given file name */ unsigned int clevel; /* maximum level of given file name */ struct task_struct *task; /* lookup and create consistency */ struct task_struct *cp_task; /* separate cp/wb IO stats*/ nid_t i_xattr_nid; /* node id that contains xattrs */ loff_t last_disk_size; /* lastly written file size */ #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; /* quota space reservation, managed internally by quota code */ qsize_t i_reserved_quota; #endif struct list_head dirty_list; /* dirty list for dirs and files */ struct list_head gdirty_list; /* linked in global dirty list */ struct list_head inmem_ilist; /* list for inmem inodes */ struct list_head inmem_pages; /* inmemory pages managed by f2fs */ struct task_struct *inmem_task; /* store inmemory task */ struct mutex inmem_lock; /* lock for inmemory pages */ struct extent_tree *extent_tree; /* cached extent_tree entry */ /* avoid racing between foreground op and gc */ struct rw_semaphore i_gc_rwsem[2]; struct rw_semaphore i_mmap_sem; struct rw_semaphore i_xattr_sem; /* avoid racing between reading and changing EAs */ int i_extra_isize; /* size of extra space located in i_addr */ kprojid_t i_projid; /* id for project quota */ int i_inline_xattr_size; /* inline xattr size */ struct timespec64 i_crtime; /* inode creation time */ struct timespec64 i_disk_time[4];/* inode disk times */ }; static inline void get_extent_info(struct extent_info *ext, struct f2fs_extent *i_ext) { ext->fofs = le32_to_cpu(i_ext->fofs); ext->blk = le32_to_cpu(i_ext->blk); ext->len = le32_to_cpu(i_ext->len); } static inline void set_raw_extent(struct extent_info *ext, struct f2fs_extent *i_ext) { i_ext->fofs = cpu_to_le32(ext->fofs); i_ext->blk = cpu_to_le32(ext->blk); i_ext->len = cpu_to_le32(ext->len); } static inline void set_extent_info(struct extent_info *ei, unsigned int fofs, u32 blk, unsigned int len) { ei->fofs = fofs; ei->blk = blk; ei->len = len; } static inline bool __is_discard_mergeable(struct discard_info *back, struct discard_info *front, unsigned int max_len) { return (back->lstart + back->len == front->lstart) && (back->len + front->len <= max_len); } static inline bool __is_discard_back_mergeable(struct discard_info *cur, struct discard_info *back, unsigned int max_len) { return __is_discard_mergeable(back, cur, max_len); } static inline bool __is_discard_front_mergeable(struct discard_info *cur, struct discard_info *front, unsigned int max_len) { return __is_discard_mergeable(cur, front, max_len); } static inline bool __is_extent_mergeable(struct extent_info *back, struct extent_info *front) { return (back->fofs + back->len == front->fofs && back->blk + back->len == front->blk); } static inline bool __is_back_mergeable(struct extent_info *cur, struct extent_info *back) { return __is_extent_mergeable(back, cur); } static inline bool __is_front_mergeable(struct extent_info *cur, struct extent_info *front) { return __is_extent_mergeable(cur, front); } extern void f2fs_mark_inode_dirty_sync(struct inode *inode, bool sync); static inline void __try_update_largest_extent(struct extent_tree *et, struct extent_node *en) { if (en->ei.len > et->largest.len) { et->largest = en->ei; et->largest_updated = true; } } /* * For free nid management */ enum nid_state { FREE_NID, /* newly added to free nid list */ PREALLOC_NID, /* it is preallocated */ MAX_NID_STATE, }; struct f2fs_nm_info { block_t nat_blkaddr; /* base disk address of NAT */ nid_t max_nid; /* maximum possible node ids */ nid_t available_nids; /* # of available node ids */ nid_t next_scan_nid; /* the next nid to be scanned */ unsigned int ram_thresh; /* control the memory footprint */ unsigned int ra_nid_pages; /* # of nid pages to be readaheaded */ unsigned int dirty_nats_ratio; /* control dirty nats ratio threshold */ /* NAT cache management */ struct radix_tree_root nat_root;/* root of the nat entry cache */ struct radix_tree_root nat_set_root;/* root of the nat set cache */ struct rw_semaphore nat_tree_lock; /* protect nat_tree_lock */ struct list_head nat_entries; /* cached nat entry list (clean) */ spinlock_t nat_list_lock; /* protect clean nat entry list */ unsigned int nat_cnt; /* the # of cached nat entries */ unsigned int dirty_nat_cnt; /* total num of nat entries in set */ unsigned int nat_blocks; /* # of nat blocks */ /* free node ids management */ struct radix_tree_root free_nid_root;/* root of the free_nid cache */ struct list_head free_nid_list; /* list for free nids excluding preallocated nids */ unsigned int nid_cnt[MAX_NID_STATE]; /* the number of free node id */ spinlock_t nid_list_lock; /* protect nid lists ops */ struct mutex build_lock; /* lock for build free nids */ unsigned char **free_nid_bitmap; unsigned char *nat_block_bitmap; unsigned short *free_nid_count; /* free nid count of NAT block */ /* for checkpoint */ char *nat_bitmap; /* NAT bitmap pointer */ unsigned int nat_bits_blocks; /* # of nat bits blocks */ unsigned char *nat_bits; /* NAT bits blocks */ unsigned char *full_nat_bits; /* full NAT pages */ unsigned char *empty_nat_bits; /* empty NAT pages */ #ifdef CONFIG_F2FS_CHECK_FS char *nat_bitmap_mir; /* NAT bitmap mirror */ #endif int bitmap_size; /* bitmap size */ }; /* * this structure is used as one of function parameters. * all the information are dedicated to a given direct node block determined * by the data offset in a file. */ struct dnode_of_data { struct inode *inode; /* vfs inode pointer */ struct page *inode_page; /* its inode page, NULL is possible */ struct page *node_page; /* cached direct node page */ nid_t nid; /* node id of the direct node block */ unsigned int ofs_in_node; /* data offset in the node page */ bool inode_page_locked; /* inode page is locked or not */ bool node_changed; /* is node block changed */ char cur_level; /* level of hole node page */ char max_level; /* level of current page located */ block_t data_blkaddr; /* block address of the node block */ }; static inline void set_new_dnode(struct dnode_of_data *dn, struct inode *inode, struct page *ipage, struct page *npage, nid_t nid) { memset(dn, 0, sizeof(*dn)); dn->inode = inode; dn->inode_page = ipage; dn->node_page = npage; dn->nid = nid; } /* * For SIT manager * * By default, there are 6 active log areas across the whole main area. * When considering hot and cold data separation to reduce cleaning overhead, * we split 3 for data logs and 3 for node logs as hot, warm, and cold types, * respectively. * In the current design, you should not change the numbers intentionally. * Instead, as a mount option such as active_logs=x, you can use 2, 4, and 6 * logs individually according to the underlying devices. (default: 6) * Just in case, on-disk layout covers maximum 16 logs that consist of 8 for * data and 8 for node logs. */ #define NR_CURSEG_DATA_TYPE (3) #define NR_CURSEG_NODE_TYPE (3) #define NR_CURSEG_TYPE (NR_CURSEG_DATA_TYPE + NR_CURSEG_NODE_TYPE) enum { CURSEG_HOT_DATA = 0, /* directory entry blocks */ CURSEG_WARM_DATA, /* data blocks */ CURSEG_COLD_DATA, /* multimedia or GCed data blocks */ CURSEG_HOT_NODE, /* direct node blocks of directory files */ CURSEG_WARM_NODE, /* direct node blocks of normal files */ CURSEG_COLD_NODE, /* indirect node blocks */ NO_CHECK_TYPE, }; struct flush_cmd { struct completion wait; struct llist_node llnode; nid_t ino; int ret; }; struct flush_cmd_control { struct task_struct *f2fs_issue_flush; /* flush thread */ wait_queue_head_t flush_wait_queue; /* waiting queue for wake-up */ atomic_t issued_flush; /* # of issued flushes */ atomic_t queued_flush; /* # of queued flushes */ struct llist_head issue_list; /* list for command issue */ struct llist_node *dispatch_list; /* list for command dispatch */ }; struct f2fs_sm_info { struct sit_info *sit_info; /* whole segment information */ struct free_segmap_info *free_info; /* free segment information */ struct dirty_seglist_info *dirty_info; /* dirty segment information */ struct curseg_info *curseg_array; /* active segment information */ struct rw_semaphore curseg_lock; /* for preventing curseg change */ block_t seg0_blkaddr; /* block address of 0'th segment */ block_t main_blkaddr; /* start block address of main area */ block_t ssa_blkaddr; /* start block address of SSA area */ unsigned int segment_count; /* total # of segments */ unsigned int main_segments; /* # of segments in main area */ unsigned int reserved_segments; /* # of reserved segments */ unsigned int ovp_segments; /* # of overprovision segments */ /* a threshold to reclaim prefree segments */ unsigned int rec_prefree_segments; /* for batched trimming */ unsigned int trim_sections; /* # of sections to trim */ struct list_head sit_entry_set; /* sit entry set list */ unsigned int ipu_policy; /* in-place-update policy */ unsigned int min_ipu_util; /* in-place-update threshold */ unsigned int min_fsync_blocks; /* threshold for fsync */ unsigned int min_seq_blocks; /* threshold for sequential blocks */ unsigned int min_hot_blocks; /* threshold for hot block allocation */ unsigned int min_ssr_sections; /* threshold to trigger SSR allocation */ /* for flush command control */ struct flush_cmd_control *fcc_info; /* for discard command control */ struct discard_cmd_control *dcc_info; }; /* * For superblock */ /* * COUNT_TYPE for monitoring * * f2fs monitors the number of several block types such as on-writeback, * dirty dentry blocks, dirty node blocks, and dirty meta blocks. */ #define WB_DATA_TYPE(p) (__is_cp_guaranteed(p) ? F2FS_WB_CP_DATA : F2FS_WB_DATA) enum count_type { F2FS_DIRTY_DENTS, F2FS_DIRTY_DATA, F2FS_DIRTY_QDATA, F2FS_DIRTY_NODES, F2FS_DIRTY_META, F2FS_INMEM_PAGES, F2FS_DIRTY_IMETA, F2FS_WB_CP_DATA, F2FS_WB_DATA, F2FS_RD_DATA, F2FS_RD_NODE, F2FS_RD_META, F2FS_DIO_WRITE, F2FS_DIO_READ, NR_COUNT_TYPE, }; /* * The below are the page types of bios used in submit_bio(). * The available types are: * DATA User data pages. It operates as async mode. * NODE Node pages. It operates as async mode. * META FS metadata pages such as SIT, NAT, CP. * NR_PAGE_TYPE The number of page types. * META_FLUSH Make sure the previous pages are written * with waiting the bio's completion * ... Only can be used with META. */ #define PAGE_TYPE_OF_BIO(type) ((type) > META ? META : (type)) enum page_type { DATA, NODE, META, NR_PAGE_TYPE, META_FLUSH, INMEM, /* the below types are used by tracepoints only. */ INMEM_DROP, INMEM_INVALIDATE, INMEM_REVOKE, IPU, OPU, }; enum temp_type { HOT = 0, /* must be zero for meta bio */ WARM, COLD, NR_TEMP_TYPE, }; enum need_lock_type { LOCK_REQ = 0, LOCK_DONE, LOCK_RETRY, }; enum cp_reason_type { CP_NO_NEEDED, CP_NON_REGULAR, CP_HARDLINK, CP_SB_NEED_CP, CP_WRONG_PINO, CP_NO_SPC_ROLL, CP_NODE_NEED_CP, CP_FASTBOOT_MODE, CP_SPEC_LOG_NUM, CP_RECOVER_DIR, }; enum iostat_type { APP_DIRECT_IO, /* app direct IOs */ APP_BUFFERED_IO, /* app buffered IOs */ APP_WRITE_IO, /* app write IOs */ APP_MAPPED_IO, /* app mapped IOs */ FS_DATA_IO, /* data IOs from kworker/fsync/reclaimer */ FS_NODE_IO, /* node IOs from kworker/fsync/reclaimer */ FS_META_IO, /* meta IOs from kworker/reclaimer */ FS_GC_DATA_IO, /* data IOs from forground gc */ FS_GC_NODE_IO, /* node IOs from forground gc */ FS_CP_DATA_IO, /* data IOs from checkpoint */ FS_CP_NODE_IO, /* node IOs from checkpoint */ FS_CP_META_IO, /* meta IOs from checkpoint */ FS_DISCARD, /* discard */ NR_IO_TYPE, }; struct f2fs_io_info { struct f2fs_sb_info *sbi; /* f2fs_sb_info pointer */ nid_t ino; /* inode number */ enum page_type type; /* contains DATA/NODE/META/META_FLUSH */ enum temp_type temp; /* contains HOT/WARM/COLD */ int op; /* contains REQ_OP_ */ int op_flags; /* req_flag_bits */ block_t new_blkaddr; /* new block address to be written */ block_t old_blkaddr; /* old block address before Cow */ struct page *page; /* page to be written */ struct page *encrypted_page; /* encrypted page */ struct list_head list; /* serialize IOs */ bool submitted; /* indicate IO submission */ int need_lock; /* indicate we need to lock cp_rwsem */ bool in_list; /* indicate fio is in io_list */ bool is_por; /* indicate IO is from recovery or not */ bool retry; /* need to reallocate block address */ enum iostat_type io_type; /* io type */ struct writeback_control *io_wbc; /* writeback control */ struct bio **bio; /* bio for ipu */ sector_t *last_block; /* last block number in bio */ unsigned char version; /* version of the node */ }; #define is_read_io(rw) ((rw) == READ) struct f2fs_bio_info { struct f2fs_sb_info *sbi; /* f2fs superblock */ struct bio *bio; /* bios to merge */ sector_t last_block_in_bio; /* last block number */ struct f2fs_io_info fio; /* store buffered io info. */ struct rw_semaphore io_rwsem; /* blocking op for bio */ spinlock_t io_lock; /* serialize DATA/NODE IOs */ struct list_head io_list; /* track fios */ }; #define FDEV(i) (sbi->devs[i]) #define RDEV(i) (raw_super->devs[i]) struct f2fs_dev_info { struct block_device *bdev; char path[MAX_PATH_LEN]; unsigned int total_segments; block_t start_blk; block_t end_blk; #ifdef CONFIG_BLK_DEV_ZONED unsigned int nr_blkz; /* Total number of zones */ unsigned long *blkz_seq; /* Bitmap indicating sequential zones */ #endif }; enum inode_type { DIR_INODE, /* for dirty dir inode */ FILE_INODE, /* for dirty regular/symlink inode */ DIRTY_META, /* for all dirtied inode metadata */ ATOMIC_FILE, /* for all atomic files */ NR_INODE_TYPE, }; /* for inner inode cache management */ struct inode_management { struct radix_tree_root ino_root; /* ino entry array */ spinlock_t ino_lock; /* for ino entry lock */ struct list_head ino_list; /* inode list head */ unsigned long ino_num; /* number of entries */ }; /* For s_flag in struct f2fs_sb_info */ enum { SBI_IS_DIRTY, /* dirty flag for checkpoint */ SBI_IS_CLOSE, /* specify unmounting */ SBI_NEED_FSCK, /* need fsck.f2fs to fix */ SBI_POR_DOING, /* recovery is doing or not */ SBI_NEED_SB_WRITE, /* need to recover superblock */ SBI_NEED_CP, /* need to checkpoint */ SBI_IS_SHUTDOWN, /* shutdown by ioctl */ SBI_IS_RECOVERED, /* recovered orphan/data */ SBI_CP_DISABLED, /* CP was disabled last mount */ SBI_CP_DISABLED_QUICK, /* CP was disabled quickly */ SBI_QUOTA_NEED_FLUSH, /* need to flush quota info in CP */ SBI_QUOTA_SKIP_FLUSH, /* skip flushing quota in current CP */ SBI_QUOTA_NEED_REPAIR, /* quota file may be corrupted */ SBI_IS_RESIZEFS, /* resizefs is in process */ }; enum { CP_TIME, REQ_TIME, DISCARD_TIME, GC_TIME, DISABLE_TIME, UMOUNT_DISCARD_TIMEOUT, MAX_TIME, }; enum { GC_NORMAL, GC_IDLE_CB, GC_IDLE_GREEDY, GC_URGENT, }; enum { WHINT_MODE_OFF, /* not pass down write hints */ WHINT_MODE_USER, /* try to pass down hints given by users */ WHINT_MODE_FS, /* pass down hints with F2FS policy */ }; enum { ALLOC_MODE_DEFAULT, /* stay default */ ALLOC_MODE_REUSE, /* reuse segments as much as possible */ }; enum fsync_mode { FSYNC_MODE_POSIX, /* fsync follows posix semantics */ FSYNC_MODE_STRICT, /* fsync behaves in line with ext4 */ FSYNC_MODE_NOBARRIER, /* fsync behaves nobarrier based on posix */ }; #ifdef CONFIG_FS_ENCRYPTION #define DUMMY_ENCRYPTION_ENABLED(sbi) \ (unlikely(F2FS_OPTION(sbi).test_dummy_encryption)) #else #define DUMMY_ENCRYPTION_ENABLED(sbi) (0) #endif struct f2fs_sb_info { struct super_block *sb; /* pointer to VFS super block */ struct proc_dir_entry *s_proc; /* proc entry */ struct f2fs_super_block *raw_super; /* raw super block pointer */ struct rw_semaphore sb_lock; /* lock for raw super block */ int valid_super_block; /* valid super block no */ unsigned long s_flag; /* flags for sbi */ struct mutex writepages; /* mutex for writepages() */ #ifdef CONFIG_BLK_DEV_ZONED unsigned int blocks_per_blkz; /* F2FS blocks per zone */ unsigned int log_blocks_per_blkz; /* log2 F2FS blocks per zone */ #endif /* for node-related operations */ struct f2fs_nm_info *nm_info; /* node manager */ struct inode *node_inode; /* cache node blocks */ /* for segment-related operations */ struct f2fs_sm_info *sm_info; /* segment manager */ /* for bio operations */ struct f2fs_bio_info *write_io[NR_PAGE_TYPE]; /* for write bios */ /* keep migration IO order for LFS mode */ struct rw_semaphore io_order_lock; mempool_t *write_io_dummy; /* Dummy pages */ /* for checkpoint */ struct f2fs_checkpoint *ckpt; /* raw checkpoint pointer */ int cur_cp_pack; /* remain current cp pack */ spinlock_t cp_lock; /* for flag in ckpt */ struct inode *meta_inode; /* cache meta blocks */ struct mutex cp_mutex; /* checkpoint procedure lock */ struct rw_semaphore cp_rwsem; /* blocking FS operations */ struct rw_semaphore node_write; /* locking node writes */ struct rw_semaphore node_change; /* locking node change */ wait_queue_head_t cp_wait; unsigned long last_time[MAX_TIME]; /* to store time in jiffies */ long interval_time[MAX_TIME]; /* to store thresholds */ struct inode_management im[MAX_INO_ENTRY]; /* manage inode cache */ spinlock_t fsync_node_lock; /* for node entry lock */ struct list_head fsync_node_list; /* node list head */ unsigned int fsync_seg_id; /* sequence id */ unsigned int fsync_node_num; /* number of node entries */ /* for orphan inode, use 0'th array */ unsigned int max_orphans; /* max orphan inodes */ /* for inode management */ struct list_head inode_list[NR_INODE_TYPE]; /* dirty inode list */ spinlock_t inode_lock[NR_INODE_TYPE]; /* for dirty inode list lock */ struct mutex flush_lock; /* for flush exclusion */ /* for extent tree cache */ struct radix_tree_root extent_tree_root;/* cache extent cache entries */ struct mutex extent_tree_lock; /* locking extent radix tree */ struct list_head extent_list; /* lru list for shrinker */ spinlock_t extent_lock; /* locking extent lru list */ atomic_t total_ext_tree; /* extent tree count */ struct list_head zombie_list; /* extent zombie tree list */ atomic_t total_zombie_tree; /* extent zombie tree count */ atomic_t total_ext_node; /* extent info count */ /* basic filesystem units */ unsigned int log_sectors_per_block; /* log2 sectors per block */ unsigned int log_blocksize; /* log2 block size */ unsigned int blocksize; /* block size */ unsigned int root_ino_num; /* root inode number*/ unsigned int node_ino_num; /* node inode number*/ unsigned int meta_ino_num; /* meta inode number*/ unsigned int log_blocks_per_seg; /* log2 blocks per segment */ unsigned int blocks_per_seg; /* blocks per segment */ unsigned int segs_per_sec; /* segments per section */ unsigned int secs_per_zone; /* sections per zone */ unsigned int total_sections; /* total section count */ struct mutex resize_mutex; /* for resize exclusion */ unsigned int total_node_count; /* total node block count */ unsigned int total_valid_node_count; /* valid node block count */ loff_t max_file_blocks; /* max block index of file */ int dir_level; /* directory level */ int readdir_ra; /* readahead inode in readdir */ block_t user_block_count; /* # of user blocks */ block_t total_valid_block_count; /* # of valid blocks */ block_t discard_blks; /* discard command candidats */ block_t last_valid_block_count; /* for recovery */ block_t reserved_blocks; /* configurable reserved blocks */ block_t current_reserved_blocks; /* current reserved blocks */ /* Additional tracking for no checkpoint mode */ block_t unusable_block_count; /* # of blocks saved by last cp */ unsigned int nquota_files; /* # of quota sysfile */ struct rw_semaphore quota_sem; /* blocking cp for flags */ /* # of pages, see count_type */ atomic_t nr_pages[NR_COUNT_TYPE]; /* # of allocated blocks */ struct percpu_counter alloc_valid_block_count; /* writeback control */ atomic_t wb_sync_req[META]; /* count # of WB_SYNC threads */ /* valid inode count */ struct percpu_counter total_valid_inode_count; struct f2fs_mount_info mount_opt; /* mount options */ /* for cleaning operations */ struct mutex gc_mutex; /* mutex for GC */ struct f2fs_gc_kthread *gc_thread; /* GC thread */ unsigned int cur_victim_sec; /* current victim section num */ unsigned int gc_mode; /* current GC state */ unsigned int next_victim_seg[2]; /* next segment in victim section */ /* for skip statistic */ unsigned long long skipped_atomic_files[2]; /* FG_GC and BG_GC */ unsigned long long skipped_gc_rwsem; /* FG_GC only */ /* threshold for gc trials on pinned files */ u64 gc_pin_file_threshold; /* maximum # of trials to find a victim segment for SSR and GC */ unsigned int max_victim_search; /* migration granularity of garbage collection, unit: segment */ unsigned int migration_granularity; /* * for stat information. * one is for the LFS mode, and the other is for the SSR mode. */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info *stat_info; /* FS status information */ atomic_t meta_count[META_MAX]; /* # of meta blocks */ unsigned int segment_count[2]; /* # of allocated segments */ unsigned int block_count[2]; /* # of allocated blocks */ atomic_t inplace_count; /* # of inplace update */ atomic64_t total_hit_ext; /* # of lookup extent cache */ atomic64_t read_hit_rbtree; /* # of hit rbtree extent node */ atomic64_t read_hit_largest; /* # of hit largest extent node */ atomic64_t read_hit_cached; /* # of hit cached extent node */ atomic_t inline_xattr; /* # of inline_xattr inodes */ atomic_t inline_inode; /* # of inline_data inodes */ atomic_t inline_dir; /* # of inline_dentry inodes */ atomic_t aw_cnt; /* # of atomic writes */ atomic_t vw_cnt; /* # of volatile writes */ atomic_t max_aw_cnt; /* max # of atomic writes */ atomic_t max_vw_cnt; /* max # of volatile writes */ int bg_gc; /* background gc calls */ unsigned int io_skip_bggc; /* skip background gc for in-flight IO */ unsigned int other_skip_bggc; /* skip background gc for other reasons */ unsigned int ndirty_inode[NR_INODE_TYPE]; /* # of dirty inodes */ #endif spinlock_t stat_lock; /* lock for stat operations */ /* For app/fs IO statistics */ spinlock_t iostat_lock; unsigned long long write_iostat[NR_IO_TYPE]; bool iostat_enable; /* For sysfs suppport */ struct kobject s_kobj; struct completion s_kobj_unregister; /* For shrinker support */ struct list_head s_list; int s_ndevs; /* number of devices */ struct f2fs_dev_info *devs; /* for device list */ unsigned int dirty_device; /* for checkpoint data flush */ spinlock_t dev_lock; /* protect dirty_device */ struct mutex umount_mutex; unsigned int shrinker_run_no; /* For write statistics */ u64 sectors_written_start; u64 kbytes_written; /* Reference to checksum algorithm driver via cryptoapi */ struct crypto_shash *s_chksum_driver; /* Precomputed FS UUID checksum for seeding other checksums */ __u32 s_chksum_seed; }; struct f2fs_private_dio { struct inode *inode; void *orig_private; bio_end_io_t *orig_end_io; bool write; }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define f2fs_show_injection_info(type) \ printk_ratelimited("%sF2FS-fs : inject %s in %s of %pS\n", \ KERN_INFO, f2fs_fault_name[type], \ __func__, __builtin_return_address(0)) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info; if (!ffi->inject_rate) return false; if (!IS_FAULT_SET(ffi, type)) return false; atomic_inc(&ffi->inject_ops); if (atomic_read(&ffi->inject_ops) >= ffi->inject_rate) { atomic_set(&ffi->inject_ops, 0); return true; } return false; } #else #define f2fs_show_injection_info(type) do { } while (0) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { return false; } #endif /* * Test if the mounted volume is a multi-device volume. * - For a single regular disk volume, sbi->s_ndevs is 0. * - For a single zoned disk volume, sbi->s_ndevs is 1. * - For a multi-device volume, sbi->s_ndevs is always 2 or more. */ static inline bool f2fs_is_multi_device(struct f2fs_sb_info *sbi) { return sbi->s_ndevs > 1; } /* For write statistics. Suppose sector size is 512 bytes, * and the return value is in kbytes. s is of struct f2fs_sb_info. */ #define BD_PART_WRITTEN(s) \ (((u64)part_stat_read((s)->sb->s_bdev->bd_part, sectors[STAT_WRITE]) - \ (s)->sectors_written_start) >> 1) static inline void f2fs_update_time(struct f2fs_sb_info *sbi, int type) { unsigned long now = jiffies; sbi->last_time[type] = now; /* DISCARD_TIME and GC_TIME are based on REQ_TIME */ if (type == REQ_TIME) { sbi->last_time[DISCARD_TIME] = now; sbi->last_time[GC_TIME] = now; } } static inline bool f2fs_time_over(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; return time_after(jiffies, sbi->last_time[type] + interval); } static inline unsigned int f2fs_time_to_wait(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; unsigned int wait_ms = 0; long delta; delta = (sbi->last_time[type] + interval) - jiffies; if (delta > 0) wait_ms = jiffies_to_msecs(delta); return wait_ms; } /* * Inline functions */ static inline u32 __f2fs_crc32(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { struct { struct shash_desc shash; char ctx[4]; } desc; int err; BUG_ON(crypto_shash_descsize(sbi->s_chksum_driver) != sizeof(desc.ctx)); desc.shash.tfm = sbi->s_chksum_driver; *(u32 *)desc.ctx = crc; err = crypto_shash_update(&desc.shash, address, length); BUG_ON(err); return *(u32 *)desc.ctx; } static inline u32 f2fs_crc32(struct f2fs_sb_info *sbi, const void *address, unsigned int length) { return __f2fs_crc32(sbi, F2FS_SUPER_MAGIC, address, length); } static inline bool f2fs_crc_valid(struct f2fs_sb_info *sbi, __u32 blk_crc, void *buf, size_t buf_size) { return f2fs_crc32(sbi, buf, buf_size) == blk_crc; } static inline u32 f2fs_chksum(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { return __f2fs_crc32(sbi, crc, address, length); } static inline struct f2fs_inode_info *F2FS_I(struct inode *inode) { return container_of(inode, struct f2fs_inode_info, vfs_inode); } static inline struct f2fs_sb_info *F2FS_SB(struct super_block *sb) { return sb->s_fs_info; } static inline struct f2fs_sb_info *F2FS_I_SB(struct inode *inode) { return F2FS_SB(inode->i_sb); } static inline struct f2fs_sb_info *F2FS_M_SB(struct address_space *mapping) { return F2FS_I_SB(mapping->host); } static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page->mapping); } static inline struct f2fs_super_block *F2FS_RAW_SUPER(struct f2fs_sb_info *sbi) { return (struct f2fs_super_block *)(sbi->raw_super); } static inline struct f2fs_checkpoint *F2FS_CKPT(struct f2fs_sb_info *sbi) { return (struct f2fs_checkpoint *)(sbi->ckpt); } static inline struct f2fs_node *F2FS_NODE(struct page *page) { return (struct f2fs_node *)page_address(page); } static inline struct f2fs_inode *F2FS_INODE(struct page *page) { return &((struct f2fs_node *)page_address(page))->i; } static inline struct f2fs_nm_info *NM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_nm_info *)(sbi->nm_info); } static inline struct f2fs_sm_info *SM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_sm_info *)(sbi->sm_info); } static inline struct sit_info *SIT_I(struct f2fs_sb_info *sbi) { return (struct sit_info *)(SM_I(sbi)->sit_info); } static inline struct free_segmap_info *FREE_I(struct f2fs_sb_info *sbi) { return (struct free_segmap_info *)(SM_I(sbi)->free_info); } static inline struct dirty_seglist_info *DIRTY_I(struct f2fs_sb_info *sbi) { return (struct dirty_seglist_info *)(SM_I(sbi)->dirty_info); } static inline struct address_space *META_MAPPING(struct f2fs_sb_info *sbi) { return sbi->meta_inode->i_mapping; } static inline struct address_space *NODE_MAPPING(struct f2fs_sb_info *sbi) { return sbi->node_inode->i_mapping; } static inline bool is_sbi_flag_set(struct f2fs_sb_info *sbi, unsigned int type) { return test_bit(type, &sbi->s_flag); } static inline void set_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { set_bit(type, &sbi->s_flag); } static inline void clear_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { clear_bit(type, &sbi->s_flag); } static inline unsigned long long cur_cp_version(struct f2fs_checkpoint *cp) { return le64_to_cpu(cp->checkpoint_ver); } static inline unsigned long f2fs_qf_ino(struct super_block *sb, int type) { if (type < F2FS_MAX_QUOTAS) return le32_to_cpu(F2FS_SB(sb)->raw_super->qf_ino[type]); return 0; } static inline __u64 cur_cp_crc(struct f2fs_checkpoint *cp) { size_t crc_offset = le32_to_cpu(cp->checksum_offset); return le32_to_cpu(*((__le32 *)((unsigned char *)cp + crc_offset))); } static inline bool __is_set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags = le32_to_cpu(cp->ckpt_flags); return ckpt_flags & f; } static inline bool is_set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { return __is_set_ckpt_flags(F2FS_CKPT(sbi), f); } static inline void __set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags |= f; cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __set_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void __clear_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags &= (~f); cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void clear_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void disable_nat_bits(struct f2fs_sb_info *sbi, bool lock) { unsigned long flags; /* * In order to re-enable nat_bits we need to call fsck.f2fs by * set_sbi_flag(sbi, SBI_NEED_FSCK). But it may give huge cost, * so let's rely on regular fsck or unclean shutdown. */ if (lock) spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), CP_NAT_BITS_FLAG); kvfree(NM_I(sbi)->nat_bits); NM_I(sbi)->nat_bits = NULL; if (lock) spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline bool enabled_nat_bits(struct f2fs_sb_info *sbi, struct cp_control *cpc) { bool set = is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG); return (cpc) ? (cpc->reason & CP_UMOUNT) && set : set; } static inline void f2fs_lock_op(struct f2fs_sb_info *sbi) { down_read(&sbi->cp_rwsem); } static inline int f2fs_trylock_op(struct f2fs_sb_info *sbi) { return down_read_trylock(&sbi->cp_rwsem); } static inline void f2fs_unlock_op(struct f2fs_sb_info *sbi) { up_read(&sbi->cp_rwsem); } static inline void f2fs_lock_all(struct f2fs_sb_info *sbi) { down_write(&sbi->cp_rwsem); } static inline void f2fs_unlock_all(struct f2fs_sb_info *sbi) { up_write(&sbi->cp_rwsem); } static inline int __get_cp_reason(struct f2fs_sb_info *sbi) { int reason = CP_SYNC; if (test_opt(sbi, FASTBOOT)) reason = CP_FASTBOOT; if (is_sbi_flag_set(sbi, SBI_IS_CLOSE)) reason = CP_UMOUNT; return reason; } static inline bool __remain_node_summaries(int reason) { return (reason & (CP_UMOUNT | CP_FASTBOOT)); } static inline bool __exist_node_summaries(struct f2fs_sb_info *sbi) { return (is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG) || is_set_ckpt_flags(sbi, CP_FASTBOOT_FLAG)); } /* * Check whether the inode has blocks or not */ static inline int F2FS_HAS_BLOCKS(struct inode *inode) { block_t xattr_block = F2FS_I(inode)->i_xattr_nid ? 1 : 0; return (inode->i_blocks >> F2FS_LOG_SECTORS_PER_BLOCK) > xattr_block; } static inline bool f2fs_has_xattr_block(unsigned int ofs) { return ofs == XATTR_NODE_OFFSET; } static inline bool __allow_reserved_blocks(struct f2fs_sb_info *sbi, struct inode *inode, bool cap) { if (!inode) return true; if (!test_opt(sbi, RESERVE_ROOT)) return false; if (IS_NOQUOTA(inode)) return true; if (uid_eq(F2FS_OPTION(sbi).s_resuid, current_fsuid())) return true; if (!gid_eq(F2FS_OPTION(sbi).s_resgid, GLOBAL_ROOT_GID) && in_group_p(F2FS_OPTION(sbi).s_resgid)) return true; if (cap && capable(CAP_SYS_RESOURCE)) return true; return false; } static inline void f2fs_i_blocks_write(struct inode *, block_t, bool, bool); static inline int inc_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, blkcnt_t *count) { blkcnt_t diff = 0, release = 0; block_t avail_user_block_count; int ret; ret = dquot_reserve_block(inode, *count); if (ret) return ret; if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); release = *count; goto enospc; } /* * let's increase this in prior to actual block count change in order * for f2fs_sync_file to avoid data races when deciding checkpoint. */ percpu_counter_add(&sbi->alloc_valid_block_count, (*count)); spin_lock(&sbi->stat_lock); sbi->total_valid_block_count += (block_t)(*count); avail_user_block_count = sbi->user_block_count - sbi->current_reserved_blocks; if (!__allow_reserved_blocks(sbi, inode, true)) avail_user_block_count -= F2FS_OPTION(sbi).root_reserved_blocks; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) { if (avail_user_block_count > sbi->unusable_block_count) avail_user_block_count -= sbi->unusable_block_count; else avail_user_block_count = 0; } if (unlikely(sbi->total_valid_block_count > avail_user_block_count)) { diff = sbi->total_valid_block_count - avail_user_block_count; if (diff > *count) diff = *count; *count -= diff; release = diff; sbi->total_valid_block_count -= diff; if (!*count) { spin_unlock(&sbi->stat_lock); goto enospc; } } spin_unlock(&sbi->stat_lock); if (unlikely(release)) { percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); } f2fs_i_blocks_write(inode, *count, true, true); return 0; enospc: percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); return -ENOSPC; } __printf(2, 3) void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...); #define f2fs_err(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_ERR fmt, ##__VA_ARGS__) #define f2fs_warn(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_WARNING fmt, ##__VA_ARGS__) #define f2fs_notice(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_NOTICE fmt, ##__VA_ARGS__) #define f2fs_info(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_INFO fmt, ##__VA_ARGS__) #define f2fs_debug(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_DEBUG fmt, ##__VA_ARGS__) static inline void dec_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, block_t count) { blkcnt_t sectors = count << F2FS_LOG_SECTORS_PER_BLOCK; spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, sbi->total_valid_block_count < (block_t) count); sbi->total_valid_block_count -= (block_t)count; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks = min(sbi->reserved_blocks, sbi->current_reserved_blocks + count); spin_unlock(&sbi->stat_lock); if (unlikely(inode->i_blocks < sectors)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu, sectors:%llu", inode->i_ino, (unsigned long long)inode->i_blocks, (unsigned long long)sectors); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, count, false, true); } static inline void inc_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_inc(&sbi->nr_pages[count_type]); if (count_type == F2FS_DIRTY_DENTS || count_type == F2FS_DIRTY_NODES || count_type == F2FS_DIRTY_META || count_type == F2FS_DIRTY_QDATA || count_type == F2FS_DIRTY_IMETA) set_sbi_flag(sbi, SBI_IS_DIRTY); } static inline void inode_inc_dirty_pages(struct inode *inode) { atomic_inc(&F2FS_I(inode)->dirty_pages); inc_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) inc_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline void dec_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_dec(&sbi->nr_pages[count_type]); } static inline void inode_dec_dirty_pages(struct inode *inode) { if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) && !S_ISLNK(inode->i_mode)) return; atomic_dec(&F2FS_I(inode)->dirty_pages); dec_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) dec_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline s64 get_pages(struct f2fs_sb_info *sbi, int count_type) { return atomic_read(&sbi->nr_pages[count_type]); } static inline int get_dirty_pages(struct inode *inode) { return atomic_read(&F2FS_I(inode)->dirty_pages); } static inline int get_blocktype_secs(struct f2fs_sb_info *sbi, int block_type) { unsigned int pages_per_sec = sbi->segs_per_sec * sbi->blocks_per_seg; unsigned int segs = (get_pages(sbi, block_type) + pages_per_sec - 1) >> sbi->log_blocks_per_seg; return segs / sbi->segs_per_sec; } static inline block_t valid_user_blocks(struct f2fs_sb_info *sbi) { return sbi->total_valid_block_count; } static inline block_t discard_blocks(struct f2fs_sb_info *sbi) { return sbi->discard_blks; } static inline unsigned long __bitmap_size(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); /* return NAT or SIT bitmap */ if (flag == NAT_BITMAP) return le32_to_cpu(ckpt->nat_ver_bitmap_bytesize); else if (flag == SIT_BITMAP) return le32_to_cpu(ckpt->sit_ver_bitmap_bytesize); return 0; } static inline block_t __cp_payload(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_payload); } static inline void *__bitmap_ptr(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); int offset; if (is_set_ckpt_flags(sbi, CP_LARGE_NAT_BITMAP_FLAG)) { offset = (flag == SIT_BITMAP) ? le32_to_cpu(ckpt->nat_ver_bitmap_bytesize) : 0; /* * if large_nat_bitmap feature is enabled, leave checksum * protection for all nat/sit bitmaps. */ return &ckpt->sit_nat_version_bitmap + offset + sizeof(__le32); } if (__cp_payload(sbi) > 0) { if (flag == NAT_BITMAP) return &ckpt->sit_nat_version_bitmap; else return (unsigned char *)ckpt + F2FS_BLKSIZE; } else { offset = (flag == NAT_BITMAP) ? le32_to_cpu(ckpt->sit_ver_bitmap_bytesize) : 0; return &ckpt->sit_nat_version_bitmap + offset; } } static inline block_t __start_cp_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 2) start_addr += sbi->blocks_per_seg; return start_addr; } static inline block_t __start_cp_next_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 1) start_addr += sbi->blocks_per_seg; return start_addr; } static inline void __set_cp_next_pack(struct f2fs_sb_info *sbi) { sbi->cur_cp_pack = (sbi->cur_cp_pack == 1) ? 2 : 1; } static inline block_t __start_sum_addr(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_CKPT(sbi)->cp_pack_start_sum); } static inline int inc_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { block_t valid_block_count; unsigned int valid_node_count, user_block_count; int err; if (is_inode) { if (inode) { err = dquot_alloc_inode(inode); if (err) return err; } } else { err = dquot_reserve_block(inode, 1); if (err) return err; } if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); goto enospc; } spin_lock(&sbi->stat_lock); valid_block_count = sbi->total_valid_block_count + sbi->current_reserved_blocks + 1; if (!__allow_reserved_blocks(sbi, inode, false)) valid_block_count += F2FS_OPTION(sbi).root_reserved_blocks; user_block_count = sbi->user_block_count; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) user_block_count -= sbi->unusable_block_count; if (unlikely(valid_block_count > user_block_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } valid_node_count = sbi->total_valid_node_count + 1; if (unlikely(valid_node_count > sbi->total_node_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } sbi->total_valid_node_count++; sbi->total_valid_block_count++; spin_unlock(&sbi->stat_lock); if (inode) { if (is_inode) f2fs_mark_inode_dirty_sync(inode, true); else f2fs_i_blocks_write(inode, 1, true, true); } percpu_counter_inc(&sbi->alloc_valid_block_count); return 0; enospc: if (is_inode) { if (inode) dquot_free_inode(inode); } else { dquot_release_reservation_block(inode, 1); } return -ENOSPC; } static inline void dec_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, !sbi->total_valid_block_count); f2fs_bug_on(sbi, !sbi->total_valid_node_count); sbi->total_valid_node_count--; sbi->total_valid_block_count--; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks++; spin_unlock(&sbi->stat_lock); if (is_inode) { dquot_free_inode(inode); } else { if (unlikely(inode->i_blocks == 0)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu", inode->i_ino, (unsigned long long)inode->i_blocks); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, 1, false, true); } } static inline unsigned int valid_node_count(struct f2fs_sb_info *sbi) { return sbi->total_valid_node_count; } static inline void inc_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_inc(&sbi->total_valid_inode_count); } static inline void dec_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_dec(&sbi->total_valid_inode_count); } static inline s64 valid_inode_count(struct f2fs_sb_info *sbi) { return percpu_counter_sum_positive(&sbi->total_valid_inode_count); } static inline struct page *f2fs_grab_cache_page(struct address_space *mapping, pgoff_t index, bool for_write) { struct page *page; if (IS_ENABLED(CONFIG_F2FS_FAULT_INJECTION)) { if (!for_write) page = find_get_page_flags(mapping, index, FGP_LOCK | FGP_ACCESSED); else page = find_lock_page(mapping, index); if (page) return page; if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_ALLOC)) { f2fs_show_injection_info(FAULT_PAGE_ALLOC); return NULL; } } if (!for_write) return grab_cache_page(mapping, index); return grab_cache_page_write_begin(mapping, index, AOP_FLAG_NOFS); } static inline struct page *f2fs_pagecache_get_page( struct address_space *mapping, pgoff_t index, int fgp_flags, gfp_t gfp_mask) { if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_GET)) { f2fs_show_injection_info(FAULT_PAGE_GET); return NULL; } return pagecache_get_page(mapping, index, fgp_flags, gfp_mask); } static inline void f2fs_copy_page(struct page *src, struct page *dst) { char *src_kaddr = kmap(src); char *dst_kaddr = kmap(dst); memcpy(dst_kaddr, src_kaddr, PAGE_SIZE); kunmap(dst); kunmap(src); } static inline void f2fs_put_page(struct page *page, int unlock) { if (!page) return; if (unlock) { f2fs_bug_on(F2FS_P_SB(page), !PageLocked(page)); unlock_page(page); } put_page(page); } static inline void f2fs_put_dnode(struct dnode_of_data *dn) { if (dn->node_page) f2fs_put_page(dn->node_page, 1); if (dn->inode_page && dn->node_page != dn->inode_page) f2fs_put_page(dn->inode_page, 0); dn->node_page = NULL; dn->inode_page = NULL; } static inline struct kmem_cache *f2fs_kmem_cache_create(const char *name, size_t size) { return kmem_cache_create(name, size, 0, SLAB_RECLAIM_ACCOUNT, NULL); } static inline void *f2fs_kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags) { void *entry; entry = kmem_cache_alloc(cachep, flags); if (!entry) entry = kmem_cache_alloc(cachep, flags | __GFP_NOFAIL); return entry; } static inline struct bio *f2fs_bio_alloc(struct f2fs_sb_info *sbi, int npages, bool no_fail) { struct bio *bio; if (no_fail) { /* No failure on bio allocation */ bio = bio_alloc(GFP_NOIO, npages); if (!bio) bio = bio_alloc(GFP_NOIO | __GFP_NOFAIL, npages); return bio; } if (time_to_inject(sbi, FAULT_ALLOC_BIO)) { f2fs_show_injection_info(FAULT_ALLOC_BIO); return NULL; } return bio_alloc(GFP_KERNEL, npages); } static inline bool is_idle(struct f2fs_sb_info *sbi, int type) { if (sbi->gc_mode == GC_URGENT) return true; if (get_pages(sbi, F2FS_RD_DATA) || get_pages(sbi, F2FS_RD_NODE) || get_pages(sbi, F2FS_RD_META) || get_pages(sbi, F2FS_WB_DATA) || get_pages(sbi, F2FS_WB_CP_DATA) || get_pages(sbi, F2FS_DIO_READ) || get_pages(sbi, F2FS_DIO_WRITE)) return false; if (type != DISCARD_TIME && SM_I(sbi) && SM_I(sbi)->dcc_info && atomic_read(&SM_I(sbi)->dcc_info->queued_discard)) return false; if (SM_I(sbi) && SM_I(sbi)->fcc_info && atomic_read(&SM_I(sbi)->fcc_info->queued_flush)) return false; return f2fs_time_over(sbi, type); } static inline void f2fs_radix_tree_insert(struct radix_tree_root *root, unsigned long index, void *item) { while (radix_tree_insert(root, index, item)) cond_resched(); } #define RAW_IS_INODE(p) ((p)->footer.nid == (p)->footer.ino) static inline bool IS_INODE(struct page *page) { struct f2fs_node *p = F2FS_NODE(page); return RAW_IS_INODE(p); } static inline int offset_in_addr(struct f2fs_inode *i) { return (i->i_inline & F2FS_EXTRA_ATTR) ? (le16_to_cpu(i->i_extra_isize) / sizeof(__le32)) : 0; } static inline __le32 *blkaddr_in_node(struct f2fs_node *node) { return RAW_IS_INODE(node) ? node->i.i_addr : node->dn.addr; } static inline int f2fs_has_extra_attr(struct inode *inode); static inline block_t datablock_addr(struct inode *inode, struct page *node_page, unsigned int offset) { struct f2fs_node *raw_node; __le32 *addr_array; int base = 0; bool is_inode = IS_INODE(node_page); raw_node = F2FS_NODE(node_page); /* from GC path only */ if (is_inode) { if (!inode) base = offset_in_addr(&raw_node->i); else if (f2fs_has_extra_attr(inode)) base = get_extra_isize(inode); } addr_array = blkaddr_in_node(raw_node); return le32_to_cpu(addr_array[base + offset]); } static inline int f2fs_test_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); return mask & *addr; } static inline void f2fs_set_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr |= mask; } static inline void f2fs_clear_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr &= ~mask; } static inline int f2fs_test_and_set_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr |= mask; return ret; } static inline int f2fs_test_and_clear_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr &= ~mask; return ret; } static inline void f2fs_change_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr ^= mask; } /* * On-disk inode flags (f2fs_inode::i_flags) */ #define F2FS_SYNC_FL 0x00000008 /* Synchronous updates */ #define F2FS_IMMUTABLE_FL 0x00000010 /* Immutable file */ #define F2FS_APPEND_FL 0x00000020 /* writes to file may only append */ #define F2FS_NODUMP_FL 0x00000040 /* do not dump file */ #define F2FS_NOATIME_FL 0x00000080 /* do not update atime */ #define F2FS_INDEX_FL 0x00001000 /* hash-indexed directory */ #define F2FS_DIRSYNC_FL 0x00010000 /* dirsync behaviour (directories only) */ #define F2FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */ /* Flags that should be inherited by new inodes from their parent. */ #define F2FS_FL_INHERITED (F2FS_SYNC_FL | F2FS_NODUMP_FL | F2FS_NOATIME_FL | \ F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL) /* Flags that are appropriate for regular files (all but dir-specific ones). */ #define F2FS_REG_FLMASK (~(F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL)) /* Flags that are appropriate for non-directories/regular files. */ #define F2FS_OTHER_FLMASK (F2FS_NODUMP_FL | F2FS_NOATIME_FL) static inline __u32 f2fs_mask_flags(umode_t mode, __u32 flags) { if (S_ISDIR(mode)) return flags; else if (S_ISREG(mode)) return flags & F2FS_REG_FLMASK; else return flags & F2FS_OTHER_FLMASK; } /* used for f2fs_inode_info->flags */ enum { FI_NEW_INODE, /* indicate newly allocated inode */ FI_DIRTY_INODE, /* indicate inode is dirty or not */ FI_AUTO_RECOVER, /* indicate inode is recoverable */ FI_DIRTY_DIR, /* indicate directory has dirty pages */ FI_INC_LINK, /* need to increment i_nlink */ FI_ACL_MODE, /* indicate acl mode */ FI_NO_ALLOC, /* should not allocate any blocks */ FI_FREE_NID, /* free allocated nide */ FI_NO_EXTENT, /* not to use the extent cache */ FI_INLINE_XATTR, /* used for inline xattr */ FI_INLINE_DATA, /* used for inline data*/ FI_INLINE_DENTRY, /* used for inline dentry */ FI_APPEND_WRITE, /* inode has appended data */ FI_UPDATE_WRITE, /* inode has in-place-update data */ FI_NEED_IPU, /* used for ipu per file */ FI_ATOMIC_FILE, /* indicate atomic file */ FI_ATOMIC_COMMIT, /* indicate the state of atomical committing */ FI_VOLATILE_FILE, /* indicate volatile file */ FI_FIRST_BLOCK_WRITTEN, /* indicate #0 data block was written */ FI_DROP_CACHE, /* drop dirty page cache */ FI_DATA_EXIST, /* indicate data exists */ FI_INLINE_DOTS, /* indicate inline dot dentries */ FI_DO_DEFRAG, /* indicate defragment is running */ FI_DIRTY_FILE, /* indicate regular/symlink has dirty pages */ FI_NO_PREALLOC, /* indicate skipped preallocated blocks */ FI_HOT_DATA, /* indicate file is hot */ FI_EXTRA_ATTR, /* indicate file has extra attribute */ FI_PROJ_INHERIT, /* indicate file inherits projectid */ FI_PIN_FILE, /* indicate file should not be gced */ FI_ATOMIC_REVOKE_REQUEST, /* request to drop atomic data */ }; static inline void __mark_inode_dirty_flag(struct inode *inode, int flag, bool set) { switch (flag) { case FI_INLINE_XATTR: case FI_INLINE_DATA: case FI_INLINE_DENTRY: case FI_NEW_INODE: if (set) return; /* fall through */ case FI_DATA_EXIST: case FI_INLINE_DOTS: case FI_PIN_FILE: f2fs_mark_inode_dirty_sync(inode, true); } } static inline void set_inode_flag(struct inode *inode, int flag) { if (!test_bit(flag, &F2FS_I(inode)->flags)) set_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, true); } static inline int is_inode_flag_set(struct inode *inode, int flag) { return test_bit(flag, &F2FS_I(inode)->flags); } static inline void clear_inode_flag(struct inode *inode, int flag) { if (test_bit(flag, &F2FS_I(inode)->flags)) clear_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, false); } static inline void set_acl_inode(struct inode *inode, umode_t mode) { F2FS_I(inode)->i_acl_mode = mode; set_inode_flag(inode, FI_ACL_MODE); f2fs_mark_inode_dirty_sync(inode, false); } static inline void f2fs_i_links_write(struct inode *inode, bool inc) { if (inc) inc_nlink(inode); else drop_nlink(inode); f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_blocks_write(struct inode *inode, block_t diff, bool add, bool claim) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); /* add = 1, claim = 1 should be dquot_reserve_block in pair */ if (add) { if (claim) dquot_claim_block(inode, diff); else dquot_alloc_block_nofail(inode, diff); } else { dquot_free_block(inode, diff); } f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_size_write(struct inode *inode, loff_t i_size) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); if (i_size_read(inode) == i_size) return; i_size_write(inode, i_size); f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_depth_write(struct inode *inode, unsigned int depth) { F2FS_I(inode)->i_current_depth = depth; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_gc_failures_write(struct inode *inode, unsigned int count) { F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN] = count; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_xnid_write(struct inode *inode, nid_t xnid) { F2FS_I(inode)->i_xattr_nid = xnid; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_pino_write(struct inode *inode, nid_t pino) { F2FS_I(inode)->i_pino = pino; f2fs_mark_inode_dirty_sync(inode, true); } static inline void get_inline_info(struct inode *inode, struct f2fs_inode *ri) { struct f2fs_inode_info *fi = F2FS_I(inode); if (ri->i_inline & F2FS_INLINE_XATTR) set_bit(FI_INLINE_XATTR, &fi->flags); if (ri->i_inline & F2FS_INLINE_DATA) set_bit(FI_INLINE_DATA, &fi->flags); if (ri->i_inline & F2FS_INLINE_DENTRY) set_bit(FI_INLINE_DENTRY, &fi->flags); if (ri->i_inline & F2FS_DATA_EXIST) set_bit(FI_DATA_EXIST, &fi->flags); if (ri->i_inline & F2FS_INLINE_DOTS) set_bit(FI_INLINE_DOTS, &fi->flags); if (ri->i_inline & F2FS_EXTRA_ATTR) set_bit(FI_EXTRA_ATTR, &fi->flags); if (ri->i_inline & F2FS_PIN_FILE) set_bit(FI_PIN_FILE, &fi->flags); } static inline void set_raw_inline(struct inode *inode, struct f2fs_inode *ri) { ri->i_inline = 0; if (is_inode_flag_set(inode, FI_INLINE_XATTR)) ri->i_inline |= F2FS_INLINE_XATTR; if (is_inode_flag_set(inode, FI_INLINE_DATA)) ri->i_inline |= F2FS_INLINE_DATA; if (is_inode_flag_set(inode, FI_INLINE_DENTRY)) ri->i_inline |= F2FS_INLINE_DENTRY; if (is_inode_flag_set(inode, FI_DATA_EXIST)) ri->i_inline |= F2FS_DATA_EXIST; if (is_inode_flag_set(inode, FI_INLINE_DOTS)) ri->i_inline |= F2FS_INLINE_DOTS; if (is_inode_flag_set(inode, FI_EXTRA_ATTR)) ri->i_inline |= F2FS_EXTRA_ATTR; if (is_inode_flag_set(inode, FI_PIN_FILE)) ri->i_inline |= F2FS_PIN_FILE; } static inline int f2fs_has_extra_attr(struct inode *inode) { return is_inode_flag_set(inode, FI_EXTRA_ATTR); } static inline int f2fs_has_inline_xattr(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_XATTR); } static inline unsigned int addrs_per_inode(struct inode *inode) { unsigned int addrs = CUR_ADDRS_PER_INODE(inode) - get_inline_xattr_addrs(inode); return ALIGN_DOWN(addrs, 1); } static inline unsigned int addrs_per_block(struct inode *inode) { return ALIGN_DOWN(DEF_ADDRS_PER_BLOCK, 1); } static inline void *inline_xattr_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); return (void *)&(ri->i_addr[DEF_ADDRS_PER_INODE - get_inline_xattr_addrs(inode)]); } static inline int inline_xattr_size(struct inode *inode) { if (f2fs_has_inline_xattr(inode)) return get_inline_xattr_addrs(inode) * sizeof(__le32); return 0; } static inline int f2fs_has_inline_data(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DATA); } static inline int f2fs_exist_data(struct inode *inode) { return is_inode_flag_set(inode, FI_DATA_EXIST); } static inline int f2fs_has_inline_dots(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DOTS); } static inline bool f2fs_is_pinned_file(struct inode *inode) { return is_inode_flag_set(inode, FI_PIN_FILE); } static inline bool f2fs_is_atomic_file(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_FILE); } static inline bool f2fs_is_commit_atomic_write(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_COMMIT); } static inline bool f2fs_is_volatile_file(struct inode *inode) { return is_inode_flag_set(inode, FI_VOLATILE_FILE); } static inline bool f2fs_is_first_block_written(struct inode *inode) { return is_inode_flag_set(inode, FI_FIRST_BLOCK_WRITTEN); } static inline bool f2fs_is_drop_cache(struct inode *inode) { return is_inode_flag_set(inode, FI_DROP_CACHE); } static inline void *inline_data_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); int extra_size = get_extra_isize(inode); return (void *)&(ri->i_addr[extra_size + DEF_INLINE_RESERVED_SIZE]); } static inline int f2fs_has_inline_dentry(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DENTRY); } static inline int is_file(struct inode *inode, int type) { return F2FS_I(inode)->i_advise & type; } static inline void set_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise |= type; f2fs_mark_inode_dirty_sync(inode, true); } static inline void clear_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise &= ~type; f2fs_mark_inode_dirty_sync(inode, true); } static inline bool f2fs_skip_inode_update(struct inode *inode, int dsync) { bool ret; if (dsync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); ret = list_empty(&F2FS_I(inode)->gdirty_list); spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } if (!is_inode_flag_set(inode, FI_AUTO_RECOVER) || file_keep_isize(inode) || i_size_read(inode) & ~PAGE_MASK) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time, &inode->i_atime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 1, &inode->i_ctime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 2, &inode->i_mtime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 3, &F2FS_I(inode)->i_crtime)) return false; down_read(&F2FS_I(inode)->i_sem); ret = F2FS_I(inode)->last_disk_size == i_size_read(inode); up_read(&F2FS_I(inode)->i_sem); return ret; } static inline bool f2fs_readonly(struct super_block *sb) { return sb_rdonly(sb); } static inline bool f2fs_cp_error(struct f2fs_sb_info *sbi) { return is_set_ckpt_flags(sbi, CP_ERROR_FLAG); } static inline bool is_dot_dotdot(const struct qstr *str) { if (str->len == 1 && str->name[0] == '.') return true; if (str->len == 2 && str->name[0] == '.' && str->name[1] == '.') return true; return false; } static inline bool f2fs_may_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (!test_opt(sbi, EXTENT_CACHE) || is_inode_flag_set(inode, FI_NO_EXTENT)) return false; /* * for recovered files during mount do not create extents * if shrinker is not registered. */ if (list_empty(&sbi->s_list)) return false; return S_ISREG(inode->i_mode); } static inline void *f2fs_kmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { void *ret; if (time_to_inject(sbi, FAULT_KMALLOC)) { f2fs_show_injection_info(FAULT_KMALLOC); return NULL; } ret = kmalloc(size, flags); if (ret) return ret; return kvmalloc(size, flags); } static inline void *f2fs_kzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kmalloc(sbi, size, flags | __GFP_ZERO); } static inline void *f2fs_kvmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { if (time_to_inject(sbi, FAULT_KVMALLOC)) { f2fs_show_injection_info(FAULT_KVMALLOC); return NULL; } return kvmalloc(size, flags); } static inline void *f2fs_kvzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kvmalloc(sbi, size, flags | __GFP_ZERO); } static inline int get_extra_isize(struct inode *inode) { return F2FS_I(inode)->i_extra_isize / sizeof(__le32); } static inline int get_inline_xattr_addrs(struct inode *inode) { return F2FS_I(inode)->i_inline_xattr_size; } #define f2fs_get_inode_mode(i) \ ((is_inode_flag_set(i, FI_ACL_MODE)) ? \ (F2FS_I(i)->i_acl_mode) : ((i)->i_mode)) #define F2FS_TOTAL_EXTRA_ATTR_SIZE \ (offsetof(struct f2fs_inode, i_extra_end) - \ offsetof(struct f2fs_inode, i_extra_isize)) \ #define F2FS_OLD_ATTRIBUTE_SIZE (offsetof(struct f2fs_inode, i_addr)) #define F2FS_FITS_IN_INODE(f2fs_inode, extra_isize, field) \ ((offsetof(typeof(*(f2fs_inode)), field) + \ sizeof((f2fs_inode)->field)) \ <= (F2FS_OLD_ATTRIBUTE_SIZE + (extra_isize))) \ static inline void f2fs_reset_iostat(struct f2fs_sb_info *sbi) { int i; spin_lock(&sbi->iostat_lock); for (i = 0; i < NR_IO_TYPE; i++) sbi->write_iostat[i] = 0; spin_unlock(&sbi->iostat_lock); } static inline void f2fs_update_iostat(struct f2fs_sb_info *sbi, enum iostat_type type, unsigned long long io_bytes) { if (!sbi->iostat_enable) return; spin_lock(&sbi->iostat_lock); sbi->write_iostat[type] += io_bytes; if (type == APP_WRITE_IO || type == APP_DIRECT_IO) sbi->write_iostat[APP_BUFFERED_IO] = sbi->write_iostat[APP_WRITE_IO] - sbi->write_iostat[APP_DIRECT_IO]; spin_unlock(&sbi->iostat_lock); } #define __is_large_section(sbi) ((sbi)->segs_per_sec > 1) #define __is_meta_io(fio) (PAGE_TYPE_OF_BIO((fio)->type) == META) bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); static inline void verify_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type) { if (!f2fs_is_valid_blkaddr(sbi, blkaddr, type)) { f2fs_err(sbi, "invalid blkaddr: %u, type: %d, run fsck to fix.", blkaddr, type); f2fs_bug_on(sbi, 1); } } static inline bool __is_valid_data_blkaddr(block_t blkaddr) { if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR) return false; return true; } static inline void f2fs_set_page_private(struct page *page, unsigned long data) { if (PagePrivate(page)) return; get_page(page); SetPagePrivate(page); set_page_private(page, data); } static inline void f2fs_clear_page_private(struct page *page) { if (!PagePrivate(page)) return; set_page_private(page, 0); ClearPagePrivate(page); f2fs_put_page(page, 0); } /* * file.c */ int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync); void f2fs_truncate_data_blocks(struct dnode_of_data *dn); int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock); int f2fs_truncate(struct inode *inode); int f2fs_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int flags); int f2fs_setattr(struct dentry *dentry, struct iattr *attr); int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end); void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count); int f2fs_precache_extents(struct inode *inode); long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid); int f2fs_pin_file_control(struct inode *inode, bool inc); /* * inode.c */ void f2fs_set_inode_flags(struct inode *inode); bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct page *page); void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct page *page); struct inode *f2fs_iget(struct super_block *sb, unsigned long ino); struct inode *f2fs_iget_retry(struct super_block *sb, unsigned long ino); int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_update_inode(struct inode *inode, struct page *node_page); void f2fs_update_inode_page(struct inode *inode); int f2fs_write_inode(struct inode *inode, struct writeback_control *wbc); void f2fs_evict_inode(struct inode *inode); void f2fs_handle_failed_inode(struct inode *inode); /* * namei.c */ int f2fs_update_extension_list(struct f2fs_sb_info *sbi, const char *name, bool hot, bool set); struct dentry *f2fs_get_parent(struct dentry *child); /* * dir.c */ unsigned char f2fs_get_de_type(struct f2fs_dir_entry *de); struct f2fs_dir_entry *f2fs_find_target_dentry(struct fscrypt_name *fname, f2fs_hash_t namehash, int *max_slots, struct f2fs_dentry_ptr *d); int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d, unsigned int start_pos, struct fscrypt_str *fstr); void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent, struct f2fs_dentry_ptr *d); struct page *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct page *dpage); void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode, unsigned int current_depth); int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots); void f2fs_drop_nlink(struct inode *dir, struct inode *inode); struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir, const struct qstr *child, struct page **res_page); struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p); ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr, struct page **page); void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de, struct page *page, struct inode *inode); void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d, const struct qstr *name, f2fs_hash_t name_hash, unsigned int bit_pos); int f2fs_add_regular_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); int f2fs_add_dentry(struct inode *dir, struct fscrypt_name *fname, struct inode *inode, nid_t ino, umode_t mode); int f2fs_do_add_link(struct inode *dir, const struct qstr *name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); int f2fs_do_tmpfile(struct inode *inode, struct inode *dir); bool f2fs_empty_dir(struct inode *dir); static inline int f2fs_add_link(struct dentry *dentry, struct inode *inode) { return f2fs_do_add_link(d_inode(dentry->d_parent), &dentry->d_name, inode, inode->i_ino, inode->i_mode); } /* * super.c */ int f2fs_inode_dirtied(struct inode *inode, bool sync); void f2fs_inode_synced(struct inode *inode); int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly); int f2fs_quota_sync(struct super_block *sb, int type); void f2fs_quota_off_umount(struct super_block *sb); int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover); int f2fs_sync_fs(struct super_block *sb, int sync); int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi); /* * hash.c */ f2fs_hash_t f2fs_dentry_hash(const struct qstr *name_info, struct fscrypt_name *fname); /* * node.c */ struct dnode_of_data; struct node_info; int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type); bool f2fs_in_warm_node_list(struct f2fs_sb_info *sbi, struct page *page); void f2fs_init_fsync_node_info(struct f2fs_sb_info *sbi); void f2fs_del_fsync_node_entry(struct f2fs_sb_info *sbi, struct page *page); void f2fs_reset_fsync_node_info(struct f2fs_sb_info *sbi); int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid, struct node_info *ni); pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs); int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode); int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from); int f2fs_truncate_xattr_node(struct inode *inode); int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi, unsigned int seq_id); int f2fs_remove_inode_page(struct inode *inode); struct page *f2fs_new_inode_page(struct inode *inode); struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs); void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid); struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid); struct page *f2fs_get_node_page_ra(struct page *parent, int start); int f2fs_move_node_page(struct page *node_page, int gc_type); int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode, struct writeback_control *wbc, bool atomic, unsigned int *seq_id); int f2fs_sync_node_pages(struct f2fs_sb_info *sbi, struct writeback_control *wbc, bool do_balance, enum iostat_type io_type); int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount); bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid); void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid); void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid); int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_recover_inline_xattr(struct inode *inode, struct page *page); int f2fs_recover_xattr_data(struct inode *inode, struct page *page); int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page); int f2fs_restore_node_summary(struct f2fs_sb_info *sbi, unsigned int segno, struct f2fs_summary_block *sum); int f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_node_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_node_manager_caches(void); void f2fs_destroy_node_manager_caches(void); /* * segment.c */ bool f2fs_need_SSR(struct f2fs_sb_info *sbi); void f2fs_register_inmem_page(struct inode *inode, struct page *page); void f2fs_drop_inmem_pages_all(struct f2fs_sb_info *sbi, bool gc_failure); void f2fs_drop_inmem_pages(struct inode *inode); void f2fs_drop_inmem_page(struct inode *inode, struct page *page); int f2fs_commit_inmem_pages(struct inode *inode); void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need); void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi); int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi); int f2fs_flush_device_cache(struct f2fs_sb_info *sbi); void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free); void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr); bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi); void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi); bool f2fs_issue_discard_timeout(struct f2fs_sb_info *sbi); void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi); block_t f2fs_get_unusable_blocks(struct f2fs_sb_info *sbi); int f2fs_disable_cp_again(struct f2fs_sb_info *sbi, block_t unusable); void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi); int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra); void allocate_segment_for_resize(struct f2fs_sb_info *sbi, int type, unsigned int start, unsigned int end); void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi); int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range); bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc); struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno); void f2fs_update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr); void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page, enum iostat_type io_type); void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio); void f2fs_outplace_write_data(struct dnode_of_data *dn, struct f2fs_io_info *fio); int f2fs_inplace_write_data(struct f2fs_io_info *fio); void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum, block_t old_blkaddr, block_t new_blkaddr, bool recover_curseg, bool recover_newaddr); void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn, block_t old_addr, block_t new_addr, unsigned char version, bool recover_curseg, bool recover_newaddr); void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page, block_t old_blkaddr, block_t *new_blkaddr, struct f2fs_summary *sum, int type, struct f2fs_io_info *fio, bool add_list); void f2fs_wait_on_page_writeback(struct page *page, enum page_type type, bool ordered, bool locked); void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr); void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr, block_t len); void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk); void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk); int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type, unsigned int val, int alloc); void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_segment_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_segment_manager_caches(void); void f2fs_destroy_segment_manager_caches(void); int f2fs_rw_hint_to_seg_type(enum rw_hint hint); enum rw_hint f2fs_io_type_to_rw_hint(struct f2fs_sb_info *sbi, enum page_type type, enum temp_type temp); /* * checkpoint.c */ void f2fs_stop_checkpoint(struct f2fs_sb_info *sbi, bool end_io); struct page *f2fs_grab_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page_nofail(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_tmp_page(struct f2fs_sb_info *sbi, pgoff_t index); bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); int f2fs_ra_meta_pages(struct f2fs_sb_info *sbi, block_t start, int nrpages, int type, bool sync); void f2fs_ra_meta_pages_cond(struct f2fs_sb_info *sbi, pgoff_t index); long f2fs_sync_meta_pages(struct f2fs_sb_info *sbi, enum page_type type, long nr_to_write, enum iostat_type io_type); void f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all); bool f2fs_exist_written_data(struct f2fs_sb_info *sbi, nid_t ino, int mode); void f2fs_set_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); bool f2fs_is_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); int f2fs_sync_inode_meta(struct f2fs_sb_info *sbi); int f2fs_acquire_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_release_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_add_orphan_inode(struct inode *inode); void f2fs_remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_recover_orphan_inodes(struct f2fs_sb_info *sbi); int f2fs_get_valid_checkpoint(struct f2fs_sb_info *sbi); void f2fs_update_dirty_page(struct inode *inode, struct page *page); void f2fs_remove_dirty_inode(struct inode *inode); int f2fs_sync_dirty_inodes(struct f2fs_sb_info *sbi, enum inode_type type); void f2fs_wait_on_all_pages_writeback(struct f2fs_sb_info *sbi); int f2fs_write_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_init_ino_entry_info(struct f2fs_sb_info *sbi); int __init f2fs_create_checkpoint_caches(void); void f2fs_destroy_checkpoint_caches(void); /* * data.c */ int f2fs_init_post_read_processing(void); void f2fs_destroy_post_read_processing(void); void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type); void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, nid_t ino, enum page_type type); void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi); int f2fs_submit_page_bio(struct f2fs_io_info *fio); int f2fs_merge_page_bio(struct f2fs_io_info *fio); void f2fs_submit_page_write(struct f2fs_io_info *fio); struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi, block_t blk_addr, struct bio *bio); int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_set_data_blkaddr(struct dnode_of_data *dn); void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr); int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count); int f2fs_reserve_new_block(struct dnode_of_data *dn); int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index); int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from); int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index); struct page *f2fs_get_read_data_page(struct inode *inode, pgoff_t index, int op_flags, bool for_write); struct page *f2fs_find_data_page(struct inode *inode, pgoff_t index); struct page *f2fs_get_lock_data_page(struct inode *inode, pgoff_t index, bool for_write); struct page *f2fs_get_new_data_page(struct inode *inode, struct page *ipage, pgoff_t index, bool new_i_size); int f2fs_do_write_data_page(struct f2fs_io_info *fio); void __do_map_lock(struct f2fs_sb_info *sbi, int flag, bool lock); int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int create, int flag); int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len); bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio); bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio); void f2fs_invalidate_page(struct page *page, unsigned int offset, unsigned int length); int f2fs_release_page(struct page *page, gfp_t wait); #ifdef CONFIG_MIGRATION int f2fs_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode); #endif bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len); void f2fs_clear_page_cache_dirty_tag(struct page *page); /* * gc.c */ int f2fs_start_gc_thread(struct f2fs_sb_info *sbi); void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi); block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode); int f2fs_gc(struct f2fs_sb_info *sbi, bool sync, bool background, unsigned int segno); void f2fs_build_gc_manager(struct f2fs_sb_info *sbi); int f2fs_resize_fs(struct f2fs_sb_info *sbi, __u64 block_count); /* * recovery.c */ int f2fs_recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only); bool f2fs_space_for_roll_forward(struct f2fs_sb_info *sbi); /* * debug.c */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info { struct list_head stat_list; struct f2fs_sb_info *sbi; int all_area_segs, sit_area_segs, nat_area_segs, ssa_area_segs; int main_area_segs, main_area_sections, main_area_zones; unsigned long long hit_largest, hit_cached, hit_rbtree; unsigned long long hit_total, total_ext; int ext_tree, zombie_tree, ext_node; int ndirty_node, ndirty_dent, ndirty_meta, ndirty_imeta; int ndirty_data, ndirty_qdata; int inmem_pages; unsigned int ndirty_dirs, ndirty_files, nquota_files, ndirty_all; int nats, dirty_nats, sits, dirty_sits; int free_nids, avail_nids, alloc_nids; int total_count, utilization; int bg_gc, nr_wb_cp_data, nr_wb_data; int nr_rd_data, nr_rd_node, nr_rd_meta; int nr_dio_read, nr_dio_write; unsigned int io_skip_bggc, other_skip_bggc; int nr_flushing, nr_flushed, flush_list_empty; int nr_discarding, nr_discarded; int nr_discard_cmd; unsigned int undiscard_blks; int inline_xattr, inline_inode, inline_dir, append, update, orphans; int aw_cnt, max_aw_cnt, vw_cnt, max_vw_cnt; unsigned int valid_count, valid_node_count, valid_inode_count, discard_blks; unsigned int bimodal, avg_vblocks; int util_free, util_valid, util_invalid; int rsvd_segs, overp_segs; int dirty_count, node_pages, meta_pages; int prefree_count, call_count, cp_count, bg_cp_count; int tot_segs, node_segs, data_segs, free_segs, free_secs; int bg_node_segs, bg_data_segs; int tot_blks, data_blks, node_blks; int bg_data_blks, bg_node_blks; unsigned long long skipped_atomic_files[2]; int curseg[NR_CURSEG_TYPE]; int cursec[NR_CURSEG_TYPE]; int curzone[NR_CURSEG_TYPE]; unsigned int meta_count[META_MAX]; unsigned int segment_count[2]; unsigned int block_count[2]; unsigned int inplace_count; unsigned long long base_mem, cache_mem, page_mem; }; static inline struct f2fs_stat_info *F2FS_STAT(struct f2fs_sb_info *sbi) { return (struct f2fs_stat_info *)sbi->stat_info; } #define stat_inc_cp_count(si) ((si)->cp_count++) #define stat_inc_bg_cp_count(si) ((si)->bg_cp_count++) #define stat_inc_call_count(si) ((si)->call_count++) #define stat_inc_bggc_count(sbi) ((sbi)->bg_gc++) #define stat_io_skip_bggc_count(sbi) ((sbi)->io_skip_bggc++) #define stat_other_skip_bggc_count(sbi) ((sbi)->other_skip_bggc++) #define stat_inc_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]++) #define stat_dec_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]--) #define stat_inc_total_hit(sbi) (atomic64_inc(&(sbi)->total_hit_ext)) #define stat_inc_rbtree_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_rbtree)) #define stat_inc_largest_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_largest)) #define stat_inc_cached_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_cached)) #define stat_inc_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_dec_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_inc_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_dec_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_inc_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_dec_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_inc_meta_count(sbi, blkaddr) \ do { \ if (blkaddr < SIT_I(sbi)->sit_base_addr) \ atomic_inc(&(sbi)->meta_count[META_CP]); \ else if (blkaddr < NM_I(sbi)->nat_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SIT]); \ else if (blkaddr < SM_I(sbi)->ssa_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_NAT]); \ else if (blkaddr < SM_I(sbi)->main_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SSA]); \ } while (0) #define stat_inc_seg_type(sbi, curseg) \ ((sbi)->segment_count[(curseg)->alloc_type]++) #define stat_inc_block_count(sbi, curseg) \ ((sbi)->block_count[(curseg)->alloc_type]++) #define stat_inc_inplace_blocks(sbi) \ (atomic_inc(&(sbi)->inplace_count)) #define stat_inc_atomic_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->aw_cnt)) #define stat_dec_atomic_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->aw_cnt)) #define stat_update_max_atomic_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->aw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_aw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_aw_cnt, cur); \ } while (0) #define stat_inc_volatile_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->vw_cnt)) #define stat_dec_volatile_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->vw_cnt)) #define stat_update_max_volatile_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->vw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_vw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_vw_cnt, cur); \ } while (0) #define stat_inc_seg_count(sbi, type, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ si->tot_segs++; \ if ((type) == SUM_TYPE_DATA) { \ si->data_segs++; \ si->bg_data_segs += (gc_type == BG_GC) ? 1 : 0; \ } else { \ si->node_segs++; \ si->bg_node_segs += (gc_type == BG_GC) ? 1 : 0; \ } \ } while (0) #define stat_inc_tot_blk_count(si, blks) \ ((si)->tot_blks += (blks)) #define stat_inc_data_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->data_blks += (blks); \ si->bg_data_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->node_blks += (blks); \ si->bg_node_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) int f2fs_build_stats(struct f2fs_sb_info *sbi); void f2fs_destroy_stats(struct f2fs_sb_info *sbi); void __init f2fs_create_root_stats(void); void f2fs_destroy_root_stats(void); #else #define stat_inc_cp_count(si) do { } while (0) #define stat_inc_bg_cp_count(si) do { } while (0) #define stat_inc_call_count(si) do { } while (0) #define stat_inc_bggc_count(si) do { } while (0) #define stat_io_skip_bggc_count(sbi) do { } while (0) #define stat_other_skip_bggc_count(sbi) do { } while (0) #define stat_inc_dirty_inode(sbi, type) do { } while (0) #define stat_dec_dirty_inode(sbi, type) do { } while (0) #define stat_inc_total_hit(sb) do { } while (0) #define stat_inc_rbtree_node_hit(sb) do { } while (0) #define stat_inc_largest_node_hit(sbi) do { } while (0) #define stat_inc_cached_node_hit(sbi) do { } while (0) #define stat_inc_inline_xattr(inode) do { } while (0) #define stat_dec_inline_xattr(inode) do { } while (0) #define stat_inc_inline_inode(inode) do { } while (0) #define stat_dec_inline_inode(inode) do { } while (0) #define stat_inc_inline_dir(inode) do { } while (0) #define stat_dec_inline_dir(inode) do { } while (0) #define stat_inc_atomic_write(inode) do { } while (0) #define stat_dec_atomic_write(inode) do { } while (0) #define stat_update_max_atomic_write(inode) do { } while (0) #define stat_inc_volatile_write(inode) do { } while (0) #define stat_dec_volatile_write(inode) do { } while (0) #define stat_update_max_volatile_write(inode) do { } while (0) #define stat_inc_meta_count(sbi, blkaddr) do { } while (0) #define stat_inc_seg_type(sbi, curseg) do { } while (0) #define stat_inc_block_count(sbi, curseg) do { } while (0) #define stat_inc_inplace_blocks(sbi) do { } while (0) #define stat_inc_seg_count(sbi, type, gc_type) do { } while (0) #define stat_inc_tot_blk_count(si, blks) do { } while (0) #define stat_inc_data_blk_count(sbi, blks, gc_type) do { } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) do { } while (0) static inline int f2fs_build_stats(struct f2fs_sb_info *sbi) { return 0; } static inline void f2fs_destroy_stats(struct f2fs_sb_info *sbi) { } static inline void __init f2fs_create_root_stats(void) { } static inline void f2fs_destroy_root_stats(void) { } #endif extern const struct file_operations f2fs_dir_operations; extern const struct file_operations f2fs_file_operations; extern const struct inode_operations f2fs_file_inode_operations; extern const struct address_space_operations f2fs_dblock_aops; extern const struct address_space_operations f2fs_node_aops; extern const struct address_space_operations f2fs_meta_aops; extern const struct inode_operations f2fs_dir_inode_operations; extern const struct inode_operations f2fs_symlink_inode_operations; extern const struct inode_operations f2fs_encrypted_symlink_inode_operations; extern const struct inode_operations f2fs_special_inode_operations; extern struct kmem_cache *f2fs_inode_entry_slab; /* * inline.c */ bool f2fs_may_inline_data(struct inode *inode); bool f2fs_may_inline_dentry(struct inode *inode); void f2fs_do_read_inline_data(struct page *page, struct page *ipage); void f2fs_truncate_inline_inode(struct inode *inode, struct page *ipage, u64 from); int f2fs_read_inline_data(struct inode *inode, struct page *page); int f2fs_convert_inline_page(struct dnode_of_data *dn, struct page *page); int f2fs_convert_inline_inode(struct inode *inode); int f2fs_write_inline_data(struct inode *inode, struct page *page); bool f2fs_recover_inline_data(struct inode *inode, struct page *npage); struct f2fs_dir_entry *f2fs_find_in_inline_dir(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); int f2fs_make_empty_inline_dir(struct inode *inode, struct inode *parent, struct page *ipage); int f2fs_add_inline_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_inline_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); bool f2fs_empty_inline_dir(struct inode *dir); int f2fs_read_inline_dir(struct file *file, struct dir_context *ctx, struct fscrypt_str *fstr); int f2fs_inline_data_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len); /* * shrinker.c */ unsigned long f2fs_shrink_count(struct shrinker *shrink, struct shrink_control *sc); unsigned long f2fs_shrink_scan(struct shrinker *shrink, struct shrink_control *sc); void f2fs_join_shrinker(struct f2fs_sb_info *sbi); void f2fs_leave_shrinker(struct f2fs_sb_info *sbi); /* * extent_cache.c */ struct rb_entry *f2fs_lookup_rb_tree(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs); struct rb_node **f2fs_lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi, struct rb_root_cached *root, struct rb_node **parent, unsigned int ofs, bool *leftmost); struct rb_entry *f2fs_lookup_rb_tree_ret(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs, struct rb_entry **prev_entry, struct rb_entry **next_entry, struct rb_node ***insert_p, struct rb_node **insert_parent, bool force, bool *leftmost); bool f2fs_check_rb_tree_consistence(struct f2fs_sb_info *sbi, struct rb_root_cached *root); unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink); bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext); void f2fs_drop_extent_tree(struct inode *inode); unsigned int f2fs_destroy_extent_node(struct inode *inode); void f2fs_destroy_extent_tree(struct inode *inode); bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs, struct extent_info *ei); void f2fs_update_extent_cache(struct dnode_of_data *dn); void f2fs_update_extent_cache_range(struct dnode_of_data *dn, pgoff_t fofs, block_t blkaddr, unsigned int len); void f2fs_init_extent_cache_info(struct f2fs_sb_info *sbi); int __init f2fs_create_extent_cache(void); void f2fs_destroy_extent_cache(void); /* * sysfs.c */ int __init f2fs_init_sysfs(void); void f2fs_exit_sysfs(void); int f2fs_register_sysfs(struct f2fs_sb_info *sbi); void f2fs_unregister_sysfs(struct f2fs_sb_info *sbi); /* * crypto support */ static inline bool f2fs_encrypted_file(struct inode *inode) { return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode); } static inline void f2fs_set_encrypted_inode(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION file_set_encrypt(inode); f2fs_set_inode_flags(inode); #endif } /* * Returns true if the reads of the inode's data need to undergo some * postprocessing step, like decryption or authenticity verification. */ static inline bool f2fs_post_read_required(struct inode *inode) { return f2fs_encrypted_file(inode); } #define F2FS_FEATURE_FUNCS(name, flagname) \ static inline int f2fs_sb_has_##name(struct f2fs_sb_info *sbi) \ { \ return F2FS_HAS_FEATURE(sbi, F2FS_FEATURE_##flagname); \ } F2FS_FEATURE_FUNCS(encrypt, ENCRYPT); F2FS_FEATURE_FUNCS(blkzoned, BLKZONED); F2FS_FEATURE_FUNCS(extra_attr, EXTRA_ATTR); F2FS_FEATURE_FUNCS(project_quota, PRJQUOTA); F2FS_FEATURE_FUNCS(inode_chksum, INODE_CHKSUM); F2FS_FEATURE_FUNCS(flexible_inline_xattr, FLEXIBLE_INLINE_XATTR); F2FS_FEATURE_FUNCS(quota_ino, QUOTA_INO); F2FS_FEATURE_FUNCS(inode_crtime, INODE_CRTIME); F2FS_FEATURE_FUNCS(lost_found, LOST_FOUND); F2FS_FEATURE_FUNCS(sb_chksum, SB_CHKSUM); #ifdef CONFIG_BLK_DEV_ZONED static inline bool f2fs_blkz_is_seq(struct f2fs_sb_info *sbi, int devi, block_t blkaddr) { unsigned int zno = blkaddr >> sbi->log_blocks_per_blkz; return test_bit(zno, FDEV(devi).blkz_seq); } #endif static inline bool f2fs_hw_should_discard(struct f2fs_sb_info *sbi) { return f2fs_sb_has_blkzoned(sbi); } static inline bool f2fs_bdev_support_discard(struct block_device *bdev) { return blk_queue_discard(bdev_get_queue(bdev)) || bdev_is_zoned(bdev); } static inline bool f2fs_hw_support_discard(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return f2fs_bdev_support_discard(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (f2fs_bdev_support_discard(FDEV(i).bdev)) return true; return false; } static inline bool f2fs_realtime_discard_enable(struct f2fs_sb_info *sbi) { return (test_opt(sbi, DISCARD) && f2fs_hw_support_discard(sbi)) || f2fs_hw_should_discard(sbi); } static inline bool f2fs_hw_is_readonly(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return bdev_read_only(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (bdev_read_only(FDEV(i).bdev)) return true; return false; } static inline void set_opt_mode(struct f2fs_sb_info *sbi, unsigned int mt) { clear_opt(sbi, ADAPTIVE); clear_opt(sbi, LFS); switch (mt) { case F2FS_MOUNT_ADAPTIVE: set_opt(sbi, ADAPTIVE); break; case F2FS_MOUNT_LFS: set_opt(sbi, LFS); break; } } static inline bool f2fs_may_encrypt(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION umode_t mode = inode->i_mode; return (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)); #else return false; #endif } static inline int block_unaligned_IO(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { unsigned int i_blkbits = READ_ONCE(inode->i_blkbits); unsigned int blocksize_mask = (1 << i_blkbits) - 1; loff_t offset = iocb->ki_pos; unsigned long align = offset | iov_iter_alignment(iter); return align & blocksize_mask; } static inline int allow_outplace_dio(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); return (test_opt(sbi, LFS) && (rw == WRITE) && !block_unaligned_IO(inode, iocb, iter)); } static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED)) return true; return false; } #ifdef CONFIG_F2FS_FAULT_INJECTION extern void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate, unsigned int type); #else #define f2fs_build_fault_attr(sbi, rate, type) do { } while (0) #endif static inline bool is_journalled_quota(struct f2fs_sb_info *sbi) { #ifdef CONFIG_QUOTA if (f2fs_sb_has_quota_ino(sbi)) return true; if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] || F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] || F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) return true; #endif return false; } #define EFSBADCRC EBADMSG /* Bad CRC detected */ #define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */ #endif /* _LINUX_F2FS_H */
// SPDX-License-Identifier: GPL-2.0 /* * fs/f2fs/f2fs.h * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ */ #ifndef _LINUX_F2FS_H #define _LINUX_F2FS_H #include <linux/uio.h> #include <linux/types.h> #include <linux/page-flags.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/crc32.h> #include <linux/magic.h> #include <linux/kobject.h> #include <linux/sched.h> #include <linux/cred.h> #include <linux/vmalloc.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/quotaops.h> #include <crypto/hash.h> #include <linux/fscrypt.h> #ifdef CONFIG_F2FS_CHECK_FS #define f2fs_bug_on(sbi, condition) BUG_ON(condition) #else #define f2fs_bug_on(sbi, condition) \ do { \ if (unlikely(condition)) { \ WARN_ON(1); \ set_sbi_flag(sbi, SBI_NEED_FSCK); \ } \ } while (0) #endif enum { FAULT_KMALLOC, FAULT_KVMALLOC, FAULT_PAGE_ALLOC, FAULT_PAGE_GET, FAULT_ALLOC_BIO, FAULT_ALLOC_NID, FAULT_ORPHAN, FAULT_BLOCK, FAULT_DIR_DEPTH, FAULT_EVICT_INODE, FAULT_TRUNCATE, FAULT_READ_IO, FAULT_CHECKPOINT, FAULT_DISCARD, FAULT_WRITE_IO, FAULT_MAX, }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define F2FS_ALL_FAULT_TYPE ((1 << FAULT_MAX) - 1) struct f2fs_fault_info { atomic_t inject_ops; unsigned int inject_rate; unsigned int inject_type; }; extern const char *f2fs_fault_name[FAULT_MAX]; #define IS_FAULT_SET(fi, type) ((fi)->inject_type & (1 << (type))) #endif /* * For mount options */ #define F2FS_MOUNT_BG_GC 0x00000001 #define F2FS_MOUNT_DISABLE_ROLL_FORWARD 0x00000002 #define F2FS_MOUNT_DISCARD 0x00000004 #define F2FS_MOUNT_NOHEAP 0x00000008 #define F2FS_MOUNT_XATTR_USER 0x00000010 #define F2FS_MOUNT_POSIX_ACL 0x00000020 #define F2FS_MOUNT_DISABLE_EXT_IDENTIFY 0x00000040 #define F2FS_MOUNT_INLINE_XATTR 0x00000080 #define F2FS_MOUNT_INLINE_DATA 0x00000100 #define F2FS_MOUNT_INLINE_DENTRY 0x00000200 #define F2FS_MOUNT_FLUSH_MERGE 0x00000400 #define F2FS_MOUNT_NOBARRIER 0x00000800 #define F2FS_MOUNT_FASTBOOT 0x00001000 #define F2FS_MOUNT_EXTENT_CACHE 0x00002000 #define F2FS_MOUNT_FORCE_FG_GC 0x00004000 #define F2FS_MOUNT_DATA_FLUSH 0x00008000 #define F2FS_MOUNT_FAULT_INJECTION 0x00010000 #define F2FS_MOUNT_ADAPTIVE 0x00020000 #define F2FS_MOUNT_LFS 0x00040000 #define F2FS_MOUNT_USRQUOTA 0x00080000 #define F2FS_MOUNT_GRPQUOTA 0x00100000 #define F2FS_MOUNT_PRJQUOTA 0x00200000 #define F2FS_MOUNT_QUOTA 0x00400000 #define F2FS_MOUNT_INLINE_XATTR_SIZE 0x00800000 #define F2FS_MOUNT_RESERVE_ROOT 0x01000000 #define F2FS_MOUNT_DISABLE_CHECKPOINT 0x02000000 #define F2FS_OPTION(sbi) ((sbi)->mount_opt) #define clear_opt(sbi, option) (F2FS_OPTION(sbi).opt &= ~F2FS_MOUNT_##option) #define set_opt(sbi, option) (F2FS_OPTION(sbi).opt |= F2FS_MOUNT_##option) #define test_opt(sbi, option) (F2FS_OPTION(sbi).opt & F2FS_MOUNT_##option) #define ver_after(a, b) (typecheck(unsigned long long, a) && \ typecheck(unsigned long long, b) && \ ((long long)((a) - (b)) > 0)) typedef u32 block_t; /* * should not change u32, since it is the on-disk block * address format, __le32. */ typedef u32 nid_t; struct f2fs_mount_info { unsigned int opt; int write_io_size_bits; /* Write IO size bits */ block_t root_reserved_blocks; /* root reserved blocks */ kuid_t s_resuid; /* reserved blocks for uid */ kgid_t s_resgid; /* reserved blocks for gid */ int active_logs; /* # of active logs */ int inline_xattr_size; /* inline xattr size */ #ifdef CONFIG_F2FS_FAULT_INJECTION struct f2fs_fault_info fault_info; /* For fault injection */ #endif #ifdef CONFIG_QUOTA /* Names of quota files with journalled quota */ char *s_qf_names[MAXQUOTAS]; int s_jquota_fmt; /* Format of quota to use */ #endif /* For which write hints are passed down to block layer */ int whint_mode; int alloc_mode; /* segment allocation policy */ int fsync_mode; /* fsync policy */ bool test_dummy_encryption; /* test dummy encryption */ block_t unusable_cap; /* Amount of space allowed to be * unusable when disabling checkpoint */ }; #define F2FS_FEATURE_ENCRYPT 0x0001 #define F2FS_FEATURE_BLKZONED 0x0002 #define F2FS_FEATURE_ATOMIC_WRITE 0x0004 #define F2FS_FEATURE_EXTRA_ATTR 0x0008 #define F2FS_FEATURE_PRJQUOTA 0x0010 #define F2FS_FEATURE_INODE_CHKSUM 0x0020 #define F2FS_FEATURE_FLEXIBLE_INLINE_XATTR 0x0040 #define F2FS_FEATURE_QUOTA_INO 0x0080 #define F2FS_FEATURE_INODE_CRTIME 0x0100 #define F2FS_FEATURE_LOST_FOUND 0x0200 #define F2FS_FEATURE_VERITY 0x0400 /* reserved */ #define F2FS_FEATURE_SB_CHKSUM 0x0800 #define __F2FS_HAS_FEATURE(raw_super, mask) \ ((raw_super->feature & cpu_to_le32(mask)) != 0) #define F2FS_HAS_FEATURE(sbi, mask) __F2FS_HAS_FEATURE(sbi->raw_super, mask) #define F2FS_SET_FEATURE(sbi, mask) \ (sbi->raw_super->feature |= cpu_to_le32(mask)) #define F2FS_CLEAR_FEATURE(sbi, mask) \ (sbi->raw_super->feature &= ~cpu_to_le32(mask)) /* * Default values for user and/or group using reserved blocks */ #define F2FS_DEF_RESUID 0 #define F2FS_DEF_RESGID 0 /* * For checkpoint manager */ enum { NAT_BITMAP, SIT_BITMAP }; #define CP_UMOUNT 0x00000001 #define CP_FASTBOOT 0x00000002 #define CP_SYNC 0x00000004 #define CP_RECOVERY 0x00000008 #define CP_DISCARD 0x00000010 #define CP_TRIMMED 0x00000020 #define CP_PAUSE 0x00000040 #define MAX_DISCARD_BLOCKS(sbi) BLKS_PER_SEC(sbi) #define DEF_MAX_DISCARD_REQUEST 8 /* issue 8 discards per round */ #define DEF_MIN_DISCARD_ISSUE_TIME 50 /* 50 ms, if exists */ #define DEF_MID_DISCARD_ISSUE_TIME 500 /* 500 ms, if device busy */ #define DEF_MAX_DISCARD_ISSUE_TIME 60000 /* 60 s, if no candidates */ #define DEF_DISCARD_URGENT_UTIL 80 /* do more discard over 80% */ #define DEF_CP_INTERVAL 60 /* 60 secs */ #define DEF_IDLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_INTERVAL 5 /* 5 secs */ #define DEF_DISABLE_QUICK_INTERVAL 1 /* 1 secs */ #define DEF_UMOUNT_DISCARD_TIMEOUT 5 /* 5 secs */ struct cp_control { int reason; __u64 trim_start; __u64 trim_end; __u64 trim_minlen; }; /* * indicate meta/data type */ enum { META_CP, META_NAT, META_SIT, META_SSA, META_MAX, META_POR, DATA_GENERIC, /* check range only */ DATA_GENERIC_ENHANCE, /* strong check on range and segment bitmap */ DATA_GENERIC_ENHANCE_READ, /* * strong check on range and segment * bitmap but no warning due to race * condition of read on truncated area * by extent_cache */ META_GENERIC, }; /* for the list of ino */ enum { ORPHAN_INO, /* for orphan ino list */ APPEND_INO, /* for append ino list */ UPDATE_INO, /* for update ino list */ TRANS_DIR_INO, /* for trasactions dir ino list */ FLUSH_INO, /* for multiple device flushing */ MAX_INO_ENTRY, /* max. list */ }; struct ino_entry { struct list_head list; /* list head */ nid_t ino; /* inode number */ unsigned int dirty_device; /* dirty device bitmap */ }; /* for the list of inodes to be GCed */ struct inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ }; struct fsync_node_entry { struct list_head list; /* list head */ struct page *page; /* warm node page pointer */ unsigned int seq_id; /* sequence id */ }; /* for the bitmap indicate blocks to be discarded */ struct discard_entry { struct list_head list; /* list head */ block_t start_blkaddr; /* start blockaddr of current segment */ unsigned char discard_map[SIT_VBLOCK_MAP_SIZE]; /* segment discard bitmap */ }; /* default discard granularity of inner discard thread, unit: block count */ #define DEFAULT_DISCARD_GRANULARITY 16 /* max discard pend list number */ #define MAX_PLIST_NUM 512 #define plist_idx(blk_num) ((blk_num) >= MAX_PLIST_NUM ? \ (MAX_PLIST_NUM - 1) : ((blk_num) - 1)) enum { D_PREP, /* initial */ D_PARTIAL, /* partially submitted */ D_SUBMIT, /* all submitted */ D_DONE, /* finished */ }; struct discard_info { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_cmd { struct rb_node rb_node; /* rb node located in rb-tree */ union { struct { block_t lstart; /* logical start address */ block_t len; /* length */ block_t start; /* actual start address in dev */ }; struct discard_info di; /* discard info */ }; struct list_head list; /* command list */ struct completion wait; /* compleation */ struct block_device *bdev; /* bdev */ unsigned short ref; /* reference count */ unsigned char state; /* state */ unsigned char queued; /* queued discard */ int error; /* bio error */ spinlock_t lock; /* for state/bio_ref updating */ unsigned short bio_ref; /* bio reference count */ }; enum { DPOLICY_BG, DPOLICY_FORCE, DPOLICY_FSTRIM, DPOLICY_UMOUNT, MAX_DPOLICY, }; struct discard_policy { int type; /* type of discard */ unsigned int min_interval; /* used for candidates exist */ unsigned int mid_interval; /* used for device busy */ unsigned int max_interval; /* used for candidates not exist */ unsigned int max_requests; /* # of discards issued per round */ unsigned int io_aware_gran; /* minimum granularity discard not be aware of I/O */ bool io_aware; /* issue discard in idle time */ bool sync; /* submit discard with REQ_SYNC flag */ bool ordered; /* issue discard by lba order */ unsigned int granularity; /* discard granularity */ int timeout; /* discard timeout for put_super */ }; struct discard_cmd_control { struct task_struct *f2fs_issue_discard; /* discard thread */ struct list_head entry_list; /* 4KB discard entry list */ struct list_head pend_list[MAX_PLIST_NUM];/* store pending entries */ struct list_head wait_list; /* store on-flushing entries */ struct list_head fstrim_list; /* in-flight discard from fstrim */ wait_queue_head_t discard_wait_queue; /* waiting queue for wake-up */ unsigned int discard_wake; /* to wake up discard thread */ struct mutex cmd_lock; unsigned int nr_discards; /* # of discards in the list */ unsigned int max_discards; /* max. discards to be issued */ unsigned int discard_granularity; /* discard granularity */ unsigned int undiscard_blks; /* # of undiscard blocks */ unsigned int next_pos; /* next discard position */ atomic_t issued_discard; /* # of issued discard */ atomic_t queued_discard; /* # of queued discard */ atomic_t discard_cmd_cnt; /* # of cached cmd count */ struct rb_root_cached root; /* root of discard rb-tree */ bool rbtree_check; /* config for consistence check */ }; /* for the list of fsync inodes, used only during recovery */ struct fsync_inode_entry { struct list_head list; /* list head */ struct inode *inode; /* vfs inode pointer */ block_t blkaddr; /* block address locating the last fsync */ block_t last_dentry; /* block address locating the last dentry */ }; #define nats_in_cursum(jnl) (le16_to_cpu((jnl)->n_nats)) #define sits_in_cursum(jnl) (le16_to_cpu((jnl)->n_sits)) #define nat_in_journal(jnl, i) ((jnl)->nat_j.entries[i].ne) #define nid_in_journal(jnl, i) ((jnl)->nat_j.entries[i].nid) #define sit_in_journal(jnl, i) ((jnl)->sit_j.entries[i].se) #define segno_in_journal(jnl, i) ((jnl)->sit_j.entries[i].segno) #define MAX_NAT_JENTRIES(jnl) (NAT_JOURNAL_ENTRIES - nats_in_cursum(jnl)) #define MAX_SIT_JENTRIES(jnl) (SIT_JOURNAL_ENTRIES - sits_in_cursum(jnl)) static inline int update_nats_in_cursum(struct f2fs_journal *journal, int i) { int before = nats_in_cursum(journal); journal->n_nats = cpu_to_le16(before + i); return before; } static inline int update_sits_in_cursum(struct f2fs_journal *journal, int i) { int before = sits_in_cursum(journal); journal->n_sits = cpu_to_le16(before + i); return before; } static inline bool __has_cursum_space(struct f2fs_journal *journal, int size, int type) { if (type == NAT_JOURNAL) return size <= MAX_NAT_JENTRIES(journal); return size <= MAX_SIT_JENTRIES(journal); } /* * ioctl commands */ #define F2FS_IOC_GETFLAGS FS_IOC_GETFLAGS #define F2FS_IOC_SETFLAGS FS_IOC_SETFLAGS #define F2FS_IOC_GETVERSION FS_IOC_GETVERSION #define F2FS_IOCTL_MAGIC 0xf5 #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) #define F2FS_IOC_RELEASE_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 4) #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) #define F2FS_IOC_GARBAGE_COLLECT _IOW(F2FS_IOCTL_MAGIC, 6, __u32) #define F2FS_IOC_WRITE_CHECKPOINT _IO(F2FS_IOCTL_MAGIC, 7) #define F2FS_IOC_DEFRAGMENT _IOWR(F2FS_IOCTL_MAGIC, 8, \ struct f2fs_defragment) #define F2FS_IOC_MOVE_RANGE _IOWR(F2FS_IOCTL_MAGIC, 9, \ struct f2fs_move_range) #define F2FS_IOC_FLUSH_DEVICE _IOW(F2FS_IOCTL_MAGIC, 10, \ struct f2fs_flush_device) #define F2FS_IOC_GARBAGE_COLLECT_RANGE _IOW(F2FS_IOCTL_MAGIC, 11, \ struct f2fs_gc_range) #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, __u32) #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32) #define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32) #define F2FS_IOC_PRECACHE_EXTENTS _IO(F2FS_IOCTL_MAGIC, 15) #define F2FS_IOC_RESIZE_FS _IOW(F2FS_IOCTL_MAGIC, 16, __u64) #define F2FS_IOC_SET_ENCRYPTION_POLICY FS_IOC_SET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_POLICY FS_IOC_GET_ENCRYPTION_POLICY #define F2FS_IOC_GET_ENCRYPTION_PWSALT FS_IOC_GET_ENCRYPTION_PWSALT /* * should be same as XFS_IOC_GOINGDOWN. * Flags for going down operation used by FS_IOC_GOINGDOWN */ #define F2FS_IOC_SHUTDOWN _IOR('X', 125, __u32) /* Shutdown */ #define F2FS_GOING_DOWN_FULLSYNC 0x0 /* going down with full sync */ #define F2FS_GOING_DOWN_METASYNC 0x1 /* going down with metadata */ #define F2FS_GOING_DOWN_NOSYNC 0x2 /* going down */ #define F2FS_GOING_DOWN_METAFLUSH 0x3 /* going down with meta flush */ #define F2FS_GOING_DOWN_NEED_FSCK 0x4 /* going down to trigger fsck */ #if defined(__KERNEL__) && defined(CONFIG_COMPAT) /* * ioctl commands in 32 bit emulation */ #define F2FS_IOC32_GETFLAGS FS_IOC32_GETFLAGS #define F2FS_IOC32_SETFLAGS FS_IOC32_SETFLAGS #define F2FS_IOC32_GETVERSION FS_IOC32_GETVERSION #endif #define F2FS_IOC_FSGETXATTR FS_IOC_FSGETXATTR #define F2FS_IOC_FSSETXATTR FS_IOC_FSSETXATTR struct f2fs_gc_range { u32 sync; u64 start; u64 len; }; struct f2fs_defragment { u64 start; u64 len; }; struct f2fs_move_range { u32 dst_fd; /* destination fd */ u64 pos_in; /* start position in src_fd */ u64 pos_out; /* start position in dst_fd */ u64 len; /* size to move */ }; struct f2fs_flush_device { u32 dev_num; /* device number to flush */ u32 segments; /* # of segments to flush */ }; /* for inline stuff */ #define DEF_INLINE_RESERVED_SIZE 1 static inline int get_extra_isize(struct inode *inode); static inline int get_inline_xattr_addrs(struct inode *inode); #define MAX_INLINE_DATA(inode) (sizeof(__le32) * \ (CUR_ADDRS_PER_INODE(inode) - \ get_inline_xattr_addrs(inode) - \ DEF_INLINE_RESERVED_SIZE)) /* for inline dir */ #define NR_INLINE_DENTRY(inode) (MAX_INLINE_DATA(inode) * BITS_PER_BYTE / \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ BITS_PER_BYTE + 1)) #define INLINE_DENTRY_BITMAP_SIZE(inode) \ DIV_ROUND_UP(NR_INLINE_DENTRY(inode), BITS_PER_BYTE) #define INLINE_RESERVED_SIZE(inode) (MAX_INLINE_DATA(inode) - \ ((SIZE_OF_DIR_ENTRY + F2FS_SLOT_LEN) * \ NR_INLINE_DENTRY(inode) + \ INLINE_DENTRY_BITMAP_SIZE(inode))) /* * For INODE and NODE manager */ /* for directory operations */ struct f2fs_dentry_ptr { struct inode *inode; void *bitmap; struct f2fs_dir_entry *dentry; __u8 (*filename)[F2FS_SLOT_LEN]; int max; int nr_bitmap; }; static inline void make_dentry_ptr_block(struct inode *inode, struct f2fs_dentry_ptr *d, struct f2fs_dentry_block *t) { d->inode = inode; d->max = NR_DENTRY_IN_BLOCK; d->nr_bitmap = SIZE_OF_DENTRY_BITMAP; d->bitmap = t->dentry_bitmap; d->dentry = t->dentry; d->filename = t->filename; } static inline void make_dentry_ptr_inline(struct inode *inode, struct f2fs_dentry_ptr *d, void *t) { int entry_cnt = NR_INLINE_DENTRY(inode); int bitmap_size = INLINE_DENTRY_BITMAP_SIZE(inode); int reserved_size = INLINE_RESERVED_SIZE(inode); d->inode = inode; d->max = entry_cnt; d->nr_bitmap = bitmap_size; d->bitmap = t; d->dentry = t + bitmap_size + reserved_size; d->filename = t + bitmap_size + reserved_size + SIZE_OF_DIR_ENTRY * entry_cnt; } /* * XATTR_NODE_OFFSET stores xattrs to one node block per file keeping -1 * as its node offset to distinguish from index node blocks. * But some bits are used to mark the node block. */ #define XATTR_NODE_OFFSET ((((unsigned int)-1) << OFFSET_BIT_SHIFT) \ >> OFFSET_BIT_SHIFT) enum { ALLOC_NODE, /* allocate a new node page if needed */ LOOKUP_NODE, /* look up a node without readahead */ LOOKUP_NODE_RA, /* * look up a node with readahead called * by get_data_block. */ }; #define DEFAULT_RETRY_IO_COUNT 8 /* maximum retry read IO count */ /* maximum retry quota flush count */ #define DEFAULT_RETRY_QUOTA_FLUSH_COUNT 8 #define F2FS_LINK_MAX 0xffffffff /* maximum link count per file */ #define MAX_DIR_RA_PAGES 4 /* maximum ra pages of dir */ /* for in-memory extent cache entry */ #define F2FS_MIN_EXTENT_LEN 64 /* minimum extent length */ /* number of extent info in extent cache we try to shrink */ #define EXTENT_CACHE_SHRINK_NUMBER 128 struct rb_entry { struct rb_node rb_node; /* rb node located in rb-tree */ unsigned int ofs; /* start offset of the entry */ unsigned int len; /* length of the entry */ }; struct extent_info { unsigned int fofs; /* start offset in a file */ unsigned int len; /* length of the extent */ u32 blk; /* start block address of the extent */ }; struct extent_node { struct rb_node rb_node; /* rb node located in rb-tree */ struct extent_info ei; /* extent info */ struct list_head list; /* node in global extent list of sbi */ struct extent_tree *et; /* extent tree pointer */ }; struct extent_tree { nid_t ino; /* inode number */ struct rb_root_cached root; /* root of extent info rb-tree */ struct extent_node *cached_en; /* recently accessed extent node */ struct extent_info largest; /* largested extent info */ struct list_head list; /* to be used by sbi->zombie_list */ rwlock_t lock; /* protect extent info rb-tree */ atomic_t node_cnt; /* # of extent node in rb-tree*/ bool largest_updated; /* largest extent updated */ }; /* * This structure is taken from ext4_map_blocks. * * Note that, however, f2fs uses NEW and MAPPED flags for f2fs_map_blocks(). */ #define F2FS_MAP_NEW (1 << BH_New) #define F2FS_MAP_MAPPED (1 << BH_Mapped) #define F2FS_MAP_UNWRITTEN (1 << BH_Unwritten) #define F2FS_MAP_FLAGS (F2FS_MAP_NEW | F2FS_MAP_MAPPED |\ F2FS_MAP_UNWRITTEN) struct f2fs_map_blocks { block_t m_pblk; block_t m_lblk; unsigned int m_len; unsigned int m_flags; pgoff_t *m_next_pgofs; /* point next possible non-hole pgofs */ pgoff_t *m_next_extent; /* point to next possible extent */ int m_seg_type; bool m_may_create; /* indicate it is from write path */ }; /* for flag in get_data_block */ enum { F2FS_GET_BLOCK_DEFAULT, F2FS_GET_BLOCK_FIEMAP, F2FS_GET_BLOCK_BMAP, F2FS_GET_BLOCK_DIO, F2FS_GET_BLOCK_PRE_DIO, F2FS_GET_BLOCK_PRE_AIO, F2FS_GET_BLOCK_PRECACHE, }; /* * i_advise uses FADVISE_XXX_BIT. We can add additional hints later. */ #define FADVISE_COLD_BIT 0x01 #define FADVISE_LOST_PINO_BIT 0x02 #define FADVISE_ENCRYPT_BIT 0x04 #define FADVISE_ENC_NAME_BIT 0x08 #define FADVISE_KEEP_SIZE_BIT 0x10 #define FADVISE_HOT_BIT 0x20 #define FADVISE_VERITY_BIT 0x40 /* reserved */ #define FADVISE_MODIFIABLE_BITS (FADVISE_COLD_BIT | FADVISE_HOT_BIT) #define file_is_cold(inode) is_file(inode, FADVISE_COLD_BIT) #define file_wrong_pino(inode) is_file(inode, FADVISE_LOST_PINO_BIT) #define file_set_cold(inode) set_file(inode, FADVISE_COLD_BIT) #define file_lost_pino(inode) set_file(inode, FADVISE_LOST_PINO_BIT) #define file_clear_cold(inode) clear_file(inode, FADVISE_COLD_BIT) #define file_got_pino(inode) clear_file(inode, FADVISE_LOST_PINO_BIT) #define file_is_encrypt(inode) is_file(inode, FADVISE_ENCRYPT_BIT) #define file_set_encrypt(inode) set_file(inode, FADVISE_ENCRYPT_BIT) #define file_clear_encrypt(inode) clear_file(inode, FADVISE_ENCRYPT_BIT) #define file_enc_name(inode) is_file(inode, FADVISE_ENC_NAME_BIT) #define file_set_enc_name(inode) set_file(inode, FADVISE_ENC_NAME_BIT) #define file_keep_isize(inode) is_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_set_keep_isize(inode) set_file(inode, FADVISE_KEEP_SIZE_BIT) #define file_is_hot(inode) is_file(inode, FADVISE_HOT_BIT) #define file_set_hot(inode) set_file(inode, FADVISE_HOT_BIT) #define file_clear_hot(inode) clear_file(inode, FADVISE_HOT_BIT) #define DEF_DIR_LEVEL 0 enum { GC_FAILURE_PIN, GC_FAILURE_ATOMIC, MAX_GC_FAILURE }; struct f2fs_inode_info { struct inode vfs_inode; /* serve a vfs inode */ unsigned long i_flags; /* keep an inode flags for ioctl */ unsigned char i_advise; /* use to give file attribute hints */ unsigned char i_dir_level; /* use for dentry level for large dir */ unsigned int i_current_depth; /* only for directory depth */ /* for gc failure statistic */ unsigned int i_gc_failures[MAX_GC_FAILURE]; unsigned int i_pino; /* parent inode number */ umode_t i_acl_mode; /* keep file acl mode temporarily */ /* Use below internally in f2fs*/ unsigned long flags; /* use to pass per-file flags */ struct rw_semaphore i_sem; /* protect fi info */ atomic_t dirty_pages; /* # of dirty pages */ f2fs_hash_t chash; /* hash value of given file name */ unsigned int clevel; /* maximum level of given file name */ struct task_struct *task; /* lookup and create consistency */ struct task_struct *cp_task; /* separate cp/wb IO stats*/ nid_t i_xattr_nid; /* node id that contains xattrs */ loff_t last_disk_size; /* lastly written file size */ #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; /* quota space reservation, managed internally by quota code */ qsize_t i_reserved_quota; #endif struct list_head dirty_list; /* dirty list for dirs and files */ struct list_head gdirty_list; /* linked in global dirty list */ struct list_head inmem_ilist; /* list for inmem inodes */ struct list_head inmem_pages; /* inmemory pages managed by f2fs */ struct task_struct *inmem_task; /* store inmemory task */ struct mutex inmem_lock; /* lock for inmemory pages */ struct extent_tree *extent_tree; /* cached extent_tree entry */ /* avoid racing between foreground op and gc */ struct rw_semaphore i_gc_rwsem[2]; struct rw_semaphore i_mmap_sem; struct rw_semaphore i_xattr_sem; /* avoid racing between reading and changing EAs */ int i_extra_isize; /* size of extra space located in i_addr */ kprojid_t i_projid; /* id for project quota */ int i_inline_xattr_size; /* inline xattr size */ struct timespec64 i_crtime; /* inode creation time */ struct timespec64 i_disk_time[4];/* inode disk times */ }; static inline void get_extent_info(struct extent_info *ext, struct f2fs_extent *i_ext) { ext->fofs = le32_to_cpu(i_ext->fofs); ext->blk = le32_to_cpu(i_ext->blk); ext->len = le32_to_cpu(i_ext->len); } static inline void set_raw_extent(struct extent_info *ext, struct f2fs_extent *i_ext) { i_ext->fofs = cpu_to_le32(ext->fofs); i_ext->blk = cpu_to_le32(ext->blk); i_ext->len = cpu_to_le32(ext->len); } static inline void set_extent_info(struct extent_info *ei, unsigned int fofs, u32 blk, unsigned int len) { ei->fofs = fofs; ei->blk = blk; ei->len = len; } static inline bool __is_discard_mergeable(struct discard_info *back, struct discard_info *front, unsigned int max_len) { return (back->lstart + back->len == front->lstart) && (back->len + front->len <= max_len); } static inline bool __is_discard_back_mergeable(struct discard_info *cur, struct discard_info *back, unsigned int max_len) { return __is_discard_mergeable(back, cur, max_len); } static inline bool __is_discard_front_mergeable(struct discard_info *cur, struct discard_info *front, unsigned int max_len) { return __is_discard_mergeable(cur, front, max_len); } static inline bool __is_extent_mergeable(struct extent_info *back, struct extent_info *front) { return (back->fofs + back->len == front->fofs && back->blk + back->len == front->blk); } static inline bool __is_back_mergeable(struct extent_info *cur, struct extent_info *back) { return __is_extent_mergeable(back, cur); } static inline bool __is_front_mergeable(struct extent_info *cur, struct extent_info *front) { return __is_extent_mergeable(cur, front); } extern void f2fs_mark_inode_dirty_sync(struct inode *inode, bool sync); static inline void __try_update_largest_extent(struct extent_tree *et, struct extent_node *en) { if (en->ei.len > et->largest.len) { et->largest = en->ei; et->largest_updated = true; } } /* * For free nid management */ enum nid_state { FREE_NID, /* newly added to free nid list */ PREALLOC_NID, /* it is preallocated */ MAX_NID_STATE, }; struct f2fs_nm_info { block_t nat_blkaddr; /* base disk address of NAT */ nid_t max_nid; /* maximum possible node ids */ nid_t available_nids; /* # of available node ids */ nid_t next_scan_nid; /* the next nid to be scanned */ unsigned int ram_thresh; /* control the memory footprint */ unsigned int ra_nid_pages; /* # of nid pages to be readaheaded */ unsigned int dirty_nats_ratio; /* control dirty nats ratio threshold */ /* NAT cache management */ struct radix_tree_root nat_root;/* root of the nat entry cache */ struct radix_tree_root nat_set_root;/* root of the nat set cache */ struct rw_semaphore nat_tree_lock; /* protect nat_tree_lock */ struct list_head nat_entries; /* cached nat entry list (clean) */ spinlock_t nat_list_lock; /* protect clean nat entry list */ unsigned int nat_cnt; /* the # of cached nat entries */ unsigned int dirty_nat_cnt; /* total num of nat entries in set */ unsigned int nat_blocks; /* # of nat blocks */ /* free node ids management */ struct radix_tree_root free_nid_root;/* root of the free_nid cache */ struct list_head free_nid_list; /* list for free nids excluding preallocated nids */ unsigned int nid_cnt[MAX_NID_STATE]; /* the number of free node id */ spinlock_t nid_list_lock; /* protect nid lists ops */ struct mutex build_lock; /* lock for build free nids */ unsigned char **free_nid_bitmap; unsigned char *nat_block_bitmap; unsigned short *free_nid_count; /* free nid count of NAT block */ /* for checkpoint */ char *nat_bitmap; /* NAT bitmap pointer */ unsigned int nat_bits_blocks; /* # of nat bits blocks */ unsigned char *nat_bits; /* NAT bits blocks */ unsigned char *full_nat_bits; /* full NAT pages */ unsigned char *empty_nat_bits; /* empty NAT pages */ #ifdef CONFIG_F2FS_CHECK_FS char *nat_bitmap_mir; /* NAT bitmap mirror */ #endif int bitmap_size; /* bitmap size */ }; /* * this structure is used as one of function parameters. * all the information are dedicated to a given direct node block determined * by the data offset in a file. */ struct dnode_of_data { struct inode *inode; /* vfs inode pointer */ struct page *inode_page; /* its inode page, NULL is possible */ struct page *node_page; /* cached direct node page */ nid_t nid; /* node id of the direct node block */ unsigned int ofs_in_node; /* data offset in the node page */ bool inode_page_locked; /* inode page is locked or not */ bool node_changed; /* is node block changed */ char cur_level; /* level of hole node page */ char max_level; /* level of current page located */ block_t data_blkaddr; /* block address of the node block */ }; static inline void set_new_dnode(struct dnode_of_data *dn, struct inode *inode, struct page *ipage, struct page *npage, nid_t nid) { memset(dn, 0, sizeof(*dn)); dn->inode = inode; dn->inode_page = ipage; dn->node_page = npage; dn->nid = nid; } /* * For SIT manager * * By default, there are 6 active log areas across the whole main area. * When considering hot and cold data separation to reduce cleaning overhead, * we split 3 for data logs and 3 for node logs as hot, warm, and cold types, * respectively. * In the current design, you should not change the numbers intentionally. * Instead, as a mount option such as active_logs=x, you can use 2, 4, and 6 * logs individually according to the underlying devices. (default: 6) * Just in case, on-disk layout covers maximum 16 logs that consist of 8 for * data and 8 for node logs. */ #define NR_CURSEG_DATA_TYPE (3) #define NR_CURSEG_NODE_TYPE (3) #define NR_CURSEG_TYPE (NR_CURSEG_DATA_TYPE + NR_CURSEG_NODE_TYPE) enum { CURSEG_HOT_DATA = 0, /* directory entry blocks */ CURSEG_WARM_DATA, /* data blocks */ CURSEG_COLD_DATA, /* multimedia or GCed data blocks */ CURSEG_HOT_NODE, /* direct node blocks of directory files */ CURSEG_WARM_NODE, /* direct node blocks of normal files */ CURSEG_COLD_NODE, /* indirect node blocks */ NO_CHECK_TYPE, }; struct flush_cmd { struct completion wait; struct llist_node llnode; nid_t ino; int ret; }; struct flush_cmd_control { struct task_struct *f2fs_issue_flush; /* flush thread */ wait_queue_head_t flush_wait_queue; /* waiting queue for wake-up */ atomic_t issued_flush; /* # of issued flushes */ atomic_t queued_flush; /* # of queued flushes */ struct llist_head issue_list; /* list for command issue */ struct llist_node *dispatch_list; /* list for command dispatch */ }; struct f2fs_sm_info { struct sit_info *sit_info; /* whole segment information */ struct free_segmap_info *free_info; /* free segment information */ struct dirty_seglist_info *dirty_info; /* dirty segment information */ struct curseg_info *curseg_array; /* active segment information */ struct rw_semaphore curseg_lock; /* for preventing curseg change */ block_t seg0_blkaddr; /* block address of 0'th segment */ block_t main_blkaddr; /* start block address of main area */ block_t ssa_blkaddr; /* start block address of SSA area */ unsigned int segment_count; /* total # of segments */ unsigned int main_segments; /* # of segments in main area */ unsigned int reserved_segments; /* # of reserved segments */ unsigned int ovp_segments; /* # of overprovision segments */ /* a threshold to reclaim prefree segments */ unsigned int rec_prefree_segments; /* for batched trimming */ unsigned int trim_sections; /* # of sections to trim */ struct list_head sit_entry_set; /* sit entry set list */ unsigned int ipu_policy; /* in-place-update policy */ unsigned int min_ipu_util; /* in-place-update threshold */ unsigned int min_fsync_blocks; /* threshold for fsync */ unsigned int min_seq_blocks; /* threshold for sequential blocks */ unsigned int min_hot_blocks; /* threshold for hot block allocation */ unsigned int min_ssr_sections; /* threshold to trigger SSR allocation */ /* for flush command control */ struct flush_cmd_control *fcc_info; /* for discard command control */ struct discard_cmd_control *dcc_info; }; /* * For superblock */ /* * COUNT_TYPE for monitoring * * f2fs monitors the number of several block types such as on-writeback, * dirty dentry blocks, dirty node blocks, and dirty meta blocks. */ #define WB_DATA_TYPE(p) (__is_cp_guaranteed(p) ? F2FS_WB_CP_DATA : F2FS_WB_DATA) enum count_type { F2FS_DIRTY_DENTS, F2FS_DIRTY_DATA, F2FS_DIRTY_QDATA, F2FS_DIRTY_NODES, F2FS_DIRTY_META, F2FS_INMEM_PAGES, F2FS_DIRTY_IMETA, F2FS_WB_CP_DATA, F2FS_WB_DATA, F2FS_RD_DATA, F2FS_RD_NODE, F2FS_RD_META, F2FS_DIO_WRITE, F2FS_DIO_READ, NR_COUNT_TYPE, }; /* * The below are the page types of bios used in submit_bio(). * The available types are: * DATA User data pages. It operates as async mode. * NODE Node pages. It operates as async mode. * META FS metadata pages such as SIT, NAT, CP. * NR_PAGE_TYPE The number of page types. * META_FLUSH Make sure the previous pages are written * with waiting the bio's completion * ... Only can be used with META. */ #define PAGE_TYPE_OF_BIO(type) ((type) > META ? META : (type)) enum page_type { DATA, NODE, META, NR_PAGE_TYPE, META_FLUSH, INMEM, /* the below types are used by tracepoints only. */ INMEM_DROP, INMEM_INVALIDATE, INMEM_REVOKE, IPU, OPU, }; enum temp_type { HOT = 0, /* must be zero for meta bio */ WARM, COLD, NR_TEMP_TYPE, }; enum need_lock_type { LOCK_REQ = 0, LOCK_DONE, LOCK_RETRY, }; enum cp_reason_type { CP_NO_NEEDED, CP_NON_REGULAR, CP_HARDLINK, CP_SB_NEED_CP, CP_WRONG_PINO, CP_NO_SPC_ROLL, CP_NODE_NEED_CP, CP_FASTBOOT_MODE, CP_SPEC_LOG_NUM, CP_RECOVER_DIR, }; enum iostat_type { APP_DIRECT_IO, /* app direct IOs */ APP_BUFFERED_IO, /* app buffered IOs */ APP_WRITE_IO, /* app write IOs */ APP_MAPPED_IO, /* app mapped IOs */ FS_DATA_IO, /* data IOs from kworker/fsync/reclaimer */ FS_NODE_IO, /* node IOs from kworker/fsync/reclaimer */ FS_META_IO, /* meta IOs from kworker/reclaimer */ FS_GC_DATA_IO, /* data IOs from forground gc */ FS_GC_NODE_IO, /* node IOs from forground gc */ FS_CP_DATA_IO, /* data IOs from checkpoint */ FS_CP_NODE_IO, /* node IOs from checkpoint */ FS_CP_META_IO, /* meta IOs from checkpoint */ FS_DISCARD, /* discard */ NR_IO_TYPE, }; struct f2fs_io_info { struct f2fs_sb_info *sbi; /* f2fs_sb_info pointer */ nid_t ino; /* inode number */ enum page_type type; /* contains DATA/NODE/META/META_FLUSH */ enum temp_type temp; /* contains HOT/WARM/COLD */ int op; /* contains REQ_OP_ */ int op_flags; /* req_flag_bits */ block_t new_blkaddr; /* new block address to be written */ block_t old_blkaddr; /* old block address before Cow */ struct page *page; /* page to be written */ struct page *encrypted_page; /* encrypted page */ struct list_head list; /* serialize IOs */ bool submitted; /* indicate IO submission */ int need_lock; /* indicate we need to lock cp_rwsem */ bool in_list; /* indicate fio is in io_list */ bool is_por; /* indicate IO is from recovery or not */ bool retry; /* need to reallocate block address */ enum iostat_type io_type; /* io type */ struct writeback_control *io_wbc; /* writeback control */ struct bio **bio; /* bio for ipu */ sector_t *last_block; /* last block number in bio */ unsigned char version; /* version of the node */ }; #define is_read_io(rw) ((rw) == READ) struct f2fs_bio_info { struct f2fs_sb_info *sbi; /* f2fs superblock */ struct bio *bio; /* bios to merge */ sector_t last_block_in_bio; /* last block number */ struct f2fs_io_info fio; /* store buffered io info. */ struct rw_semaphore io_rwsem; /* blocking op for bio */ spinlock_t io_lock; /* serialize DATA/NODE IOs */ struct list_head io_list; /* track fios */ }; #define FDEV(i) (sbi->devs[i]) #define RDEV(i) (raw_super->devs[i]) struct f2fs_dev_info { struct block_device *bdev; char path[MAX_PATH_LEN]; unsigned int total_segments; block_t start_blk; block_t end_blk; #ifdef CONFIG_BLK_DEV_ZONED unsigned int nr_blkz; /* Total number of zones */ unsigned long *blkz_seq; /* Bitmap indicating sequential zones */ #endif }; enum inode_type { DIR_INODE, /* for dirty dir inode */ FILE_INODE, /* for dirty regular/symlink inode */ DIRTY_META, /* for all dirtied inode metadata */ ATOMIC_FILE, /* for all atomic files */ NR_INODE_TYPE, }; /* for inner inode cache management */ struct inode_management { struct radix_tree_root ino_root; /* ino entry array */ spinlock_t ino_lock; /* for ino entry lock */ struct list_head ino_list; /* inode list head */ unsigned long ino_num; /* number of entries */ }; /* For s_flag in struct f2fs_sb_info */ enum { SBI_IS_DIRTY, /* dirty flag for checkpoint */ SBI_IS_CLOSE, /* specify unmounting */ SBI_NEED_FSCK, /* need fsck.f2fs to fix */ SBI_POR_DOING, /* recovery is doing or not */ SBI_NEED_SB_WRITE, /* need to recover superblock */ SBI_NEED_CP, /* need to checkpoint */ SBI_IS_SHUTDOWN, /* shutdown by ioctl */ SBI_IS_RECOVERED, /* recovered orphan/data */ SBI_CP_DISABLED, /* CP was disabled last mount */ SBI_CP_DISABLED_QUICK, /* CP was disabled quickly */ SBI_QUOTA_NEED_FLUSH, /* need to flush quota info in CP */ SBI_QUOTA_SKIP_FLUSH, /* skip flushing quota in current CP */ SBI_QUOTA_NEED_REPAIR, /* quota file may be corrupted */ SBI_IS_RESIZEFS, /* resizefs is in process */ }; enum { CP_TIME, REQ_TIME, DISCARD_TIME, GC_TIME, DISABLE_TIME, UMOUNT_DISCARD_TIMEOUT, MAX_TIME, }; enum { GC_NORMAL, GC_IDLE_CB, GC_IDLE_GREEDY, GC_URGENT, }; enum { WHINT_MODE_OFF, /* not pass down write hints */ WHINT_MODE_USER, /* try to pass down hints given by users */ WHINT_MODE_FS, /* pass down hints with F2FS policy */ }; enum { ALLOC_MODE_DEFAULT, /* stay default */ ALLOC_MODE_REUSE, /* reuse segments as much as possible */ }; enum fsync_mode { FSYNC_MODE_POSIX, /* fsync follows posix semantics */ FSYNC_MODE_STRICT, /* fsync behaves in line with ext4 */ FSYNC_MODE_NOBARRIER, /* fsync behaves nobarrier based on posix */ }; #ifdef CONFIG_FS_ENCRYPTION #define DUMMY_ENCRYPTION_ENABLED(sbi) \ (unlikely(F2FS_OPTION(sbi).test_dummy_encryption)) #else #define DUMMY_ENCRYPTION_ENABLED(sbi) (0) #endif struct f2fs_sb_info { struct super_block *sb; /* pointer to VFS super block */ struct proc_dir_entry *s_proc; /* proc entry */ struct f2fs_super_block *raw_super; /* raw super block pointer */ struct rw_semaphore sb_lock; /* lock for raw super block */ int valid_super_block; /* valid super block no */ unsigned long s_flag; /* flags for sbi */ struct mutex writepages; /* mutex for writepages() */ #ifdef CONFIG_BLK_DEV_ZONED unsigned int blocks_per_blkz; /* F2FS blocks per zone */ unsigned int log_blocks_per_blkz; /* log2 F2FS blocks per zone */ #endif /* for node-related operations */ struct f2fs_nm_info *nm_info; /* node manager */ struct inode *node_inode; /* cache node blocks */ /* for segment-related operations */ struct f2fs_sm_info *sm_info; /* segment manager */ /* for bio operations */ struct f2fs_bio_info *write_io[NR_PAGE_TYPE]; /* for write bios */ /* keep migration IO order for LFS mode */ struct rw_semaphore io_order_lock; mempool_t *write_io_dummy; /* Dummy pages */ /* for checkpoint */ struct f2fs_checkpoint *ckpt; /* raw checkpoint pointer */ int cur_cp_pack; /* remain current cp pack */ spinlock_t cp_lock; /* for flag in ckpt */ struct inode *meta_inode; /* cache meta blocks */ struct mutex cp_mutex; /* checkpoint procedure lock */ struct rw_semaphore cp_rwsem; /* blocking FS operations */ struct rw_semaphore node_write; /* locking node writes */ struct rw_semaphore node_change; /* locking node change */ wait_queue_head_t cp_wait; unsigned long last_time[MAX_TIME]; /* to store time in jiffies */ long interval_time[MAX_TIME]; /* to store thresholds */ struct inode_management im[MAX_INO_ENTRY]; /* manage inode cache */ spinlock_t fsync_node_lock; /* for node entry lock */ struct list_head fsync_node_list; /* node list head */ unsigned int fsync_seg_id; /* sequence id */ unsigned int fsync_node_num; /* number of node entries */ /* for orphan inode, use 0'th array */ unsigned int max_orphans; /* max orphan inodes */ /* for inode management */ struct list_head inode_list[NR_INODE_TYPE]; /* dirty inode list */ spinlock_t inode_lock[NR_INODE_TYPE]; /* for dirty inode list lock */ struct mutex flush_lock; /* for flush exclusion */ /* for extent tree cache */ struct radix_tree_root extent_tree_root;/* cache extent cache entries */ struct mutex extent_tree_lock; /* locking extent radix tree */ struct list_head extent_list; /* lru list for shrinker */ spinlock_t extent_lock; /* locking extent lru list */ atomic_t total_ext_tree; /* extent tree count */ struct list_head zombie_list; /* extent zombie tree list */ atomic_t total_zombie_tree; /* extent zombie tree count */ atomic_t total_ext_node; /* extent info count */ /* basic filesystem units */ unsigned int log_sectors_per_block; /* log2 sectors per block */ unsigned int log_blocksize; /* log2 block size */ unsigned int blocksize; /* block size */ unsigned int root_ino_num; /* root inode number*/ unsigned int node_ino_num; /* node inode number*/ unsigned int meta_ino_num; /* meta inode number*/ unsigned int log_blocks_per_seg; /* log2 blocks per segment */ unsigned int blocks_per_seg; /* blocks per segment */ unsigned int segs_per_sec; /* segments per section */ unsigned int secs_per_zone; /* sections per zone */ unsigned int total_sections; /* total section count */ struct mutex resize_mutex; /* for resize exclusion */ unsigned int total_node_count; /* total node block count */ unsigned int total_valid_node_count; /* valid node block count */ loff_t max_file_blocks; /* max block index of file */ int dir_level; /* directory level */ int readdir_ra; /* readahead inode in readdir */ block_t user_block_count; /* # of user blocks */ block_t total_valid_block_count; /* # of valid blocks */ block_t discard_blks; /* discard command candidats */ block_t last_valid_block_count; /* for recovery */ block_t reserved_blocks; /* configurable reserved blocks */ block_t current_reserved_blocks; /* current reserved blocks */ /* Additional tracking for no checkpoint mode */ block_t unusable_block_count; /* # of blocks saved by last cp */ unsigned int nquota_files; /* # of quota sysfile */ struct rw_semaphore quota_sem; /* blocking cp for flags */ /* # of pages, see count_type */ atomic_t nr_pages[NR_COUNT_TYPE]; /* # of allocated blocks */ struct percpu_counter alloc_valid_block_count; /* writeback control */ atomic_t wb_sync_req[META]; /* count # of WB_SYNC threads */ /* valid inode count */ struct percpu_counter total_valid_inode_count; struct f2fs_mount_info mount_opt; /* mount options */ /* for cleaning operations */ struct mutex gc_mutex; /* mutex for GC */ struct f2fs_gc_kthread *gc_thread; /* GC thread */ unsigned int cur_victim_sec; /* current victim section num */ unsigned int gc_mode; /* current GC state */ unsigned int next_victim_seg[2]; /* next segment in victim section */ /* for skip statistic */ unsigned long long skipped_atomic_files[2]; /* FG_GC and BG_GC */ unsigned long long skipped_gc_rwsem; /* FG_GC only */ /* threshold for gc trials on pinned files */ u64 gc_pin_file_threshold; /* maximum # of trials to find a victim segment for SSR and GC */ unsigned int max_victim_search; /* migration granularity of garbage collection, unit: segment */ unsigned int migration_granularity; /* * for stat information. * one is for the LFS mode, and the other is for the SSR mode. */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info *stat_info; /* FS status information */ atomic_t meta_count[META_MAX]; /* # of meta blocks */ unsigned int segment_count[2]; /* # of allocated segments */ unsigned int block_count[2]; /* # of allocated blocks */ atomic_t inplace_count; /* # of inplace update */ atomic64_t total_hit_ext; /* # of lookup extent cache */ atomic64_t read_hit_rbtree; /* # of hit rbtree extent node */ atomic64_t read_hit_largest; /* # of hit largest extent node */ atomic64_t read_hit_cached; /* # of hit cached extent node */ atomic_t inline_xattr; /* # of inline_xattr inodes */ atomic_t inline_inode; /* # of inline_data inodes */ atomic_t inline_dir; /* # of inline_dentry inodes */ atomic_t aw_cnt; /* # of atomic writes */ atomic_t vw_cnt; /* # of volatile writes */ atomic_t max_aw_cnt; /* max # of atomic writes */ atomic_t max_vw_cnt; /* max # of volatile writes */ int bg_gc; /* background gc calls */ unsigned int io_skip_bggc; /* skip background gc for in-flight IO */ unsigned int other_skip_bggc; /* skip background gc for other reasons */ unsigned int ndirty_inode[NR_INODE_TYPE]; /* # of dirty inodes */ #endif spinlock_t stat_lock; /* lock for stat operations */ /* For app/fs IO statistics */ spinlock_t iostat_lock; unsigned long long write_iostat[NR_IO_TYPE]; bool iostat_enable; /* For sysfs suppport */ struct kobject s_kobj; struct completion s_kobj_unregister; /* For shrinker support */ struct list_head s_list; int s_ndevs; /* number of devices */ struct f2fs_dev_info *devs; /* for device list */ unsigned int dirty_device; /* for checkpoint data flush */ spinlock_t dev_lock; /* protect dirty_device */ struct mutex umount_mutex; unsigned int shrinker_run_no; /* For write statistics */ u64 sectors_written_start; u64 kbytes_written; /* Reference to checksum algorithm driver via cryptoapi */ struct crypto_shash *s_chksum_driver; /* Precomputed FS UUID checksum for seeding other checksums */ __u32 s_chksum_seed; }; struct f2fs_private_dio { struct inode *inode; void *orig_private; bio_end_io_t *orig_end_io; bool write; }; #ifdef CONFIG_F2FS_FAULT_INJECTION #define f2fs_show_injection_info(type) \ printk_ratelimited("%sF2FS-fs : inject %s in %s of %pS\n", \ KERN_INFO, f2fs_fault_name[type], \ __func__, __builtin_return_address(0)) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { struct f2fs_fault_info *ffi = &F2FS_OPTION(sbi).fault_info; if (!ffi->inject_rate) return false; if (!IS_FAULT_SET(ffi, type)) return false; atomic_inc(&ffi->inject_ops); if (atomic_read(&ffi->inject_ops) >= ffi->inject_rate) { atomic_set(&ffi->inject_ops, 0); return true; } return false; } #else #define f2fs_show_injection_info(type) do { } while (0) static inline bool time_to_inject(struct f2fs_sb_info *sbi, int type) { return false; } #endif /* * Test if the mounted volume is a multi-device volume. * - For a single regular disk volume, sbi->s_ndevs is 0. * - For a single zoned disk volume, sbi->s_ndevs is 1. * - For a multi-device volume, sbi->s_ndevs is always 2 or more. */ static inline bool f2fs_is_multi_device(struct f2fs_sb_info *sbi) { return sbi->s_ndevs > 1; } /* For write statistics. Suppose sector size is 512 bytes, * and the return value is in kbytes. s is of struct f2fs_sb_info. */ #define BD_PART_WRITTEN(s) \ (((u64)part_stat_read((s)->sb->s_bdev->bd_part, sectors[STAT_WRITE]) - \ (s)->sectors_written_start) >> 1) static inline void f2fs_update_time(struct f2fs_sb_info *sbi, int type) { unsigned long now = jiffies; sbi->last_time[type] = now; /* DISCARD_TIME and GC_TIME are based on REQ_TIME */ if (type == REQ_TIME) { sbi->last_time[DISCARD_TIME] = now; sbi->last_time[GC_TIME] = now; } } static inline bool f2fs_time_over(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; return time_after(jiffies, sbi->last_time[type] + interval); } static inline unsigned int f2fs_time_to_wait(struct f2fs_sb_info *sbi, int type) { unsigned long interval = sbi->interval_time[type] * HZ; unsigned int wait_ms = 0; long delta; delta = (sbi->last_time[type] + interval) - jiffies; if (delta > 0) wait_ms = jiffies_to_msecs(delta); return wait_ms; } /* * Inline functions */ static inline u32 __f2fs_crc32(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { struct { struct shash_desc shash; char ctx[4]; } desc; int err; BUG_ON(crypto_shash_descsize(sbi->s_chksum_driver) != sizeof(desc.ctx)); desc.shash.tfm = sbi->s_chksum_driver; *(u32 *)desc.ctx = crc; err = crypto_shash_update(&desc.shash, address, length); BUG_ON(err); return *(u32 *)desc.ctx; } static inline u32 f2fs_crc32(struct f2fs_sb_info *sbi, const void *address, unsigned int length) { return __f2fs_crc32(sbi, F2FS_SUPER_MAGIC, address, length); } static inline bool f2fs_crc_valid(struct f2fs_sb_info *sbi, __u32 blk_crc, void *buf, size_t buf_size) { return f2fs_crc32(sbi, buf, buf_size) == blk_crc; } static inline u32 f2fs_chksum(struct f2fs_sb_info *sbi, u32 crc, const void *address, unsigned int length) { return __f2fs_crc32(sbi, crc, address, length); } static inline struct f2fs_inode_info *F2FS_I(struct inode *inode) { return container_of(inode, struct f2fs_inode_info, vfs_inode); } static inline struct f2fs_sb_info *F2FS_SB(struct super_block *sb) { return sb->s_fs_info; } static inline struct f2fs_sb_info *F2FS_I_SB(struct inode *inode) { return F2FS_SB(inode->i_sb); } static inline struct f2fs_sb_info *F2FS_M_SB(struct address_space *mapping) { return F2FS_I_SB(mapping->host); } static inline struct f2fs_sb_info *F2FS_P_SB(struct page *page) { return F2FS_M_SB(page_file_mapping(page)); } static inline struct f2fs_super_block *F2FS_RAW_SUPER(struct f2fs_sb_info *sbi) { return (struct f2fs_super_block *)(sbi->raw_super); } static inline struct f2fs_checkpoint *F2FS_CKPT(struct f2fs_sb_info *sbi) { return (struct f2fs_checkpoint *)(sbi->ckpt); } static inline struct f2fs_node *F2FS_NODE(struct page *page) { return (struct f2fs_node *)page_address(page); } static inline struct f2fs_inode *F2FS_INODE(struct page *page) { return &((struct f2fs_node *)page_address(page))->i; } static inline struct f2fs_nm_info *NM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_nm_info *)(sbi->nm_info); } static inline struct f2fs_sm_info *SM_I(struct f2fs_sb_info *sbi) { return (struct f2fs_sm_info *)(sbi->sm_info); } static inline struct sit_info *SIT_I(struct f2fs_sb_info *sbi) { return (struct sit_info *)(SM_I(sbi)->sit_info); } static inline struct free_segmap_info *FREE_I(struct f2fs_sb_info *sbi) { return (struct free_segmap_info *)(SM_I(sbi)->free_info); } static inline struct dirty_seglist_info *DIRTY_I(struct f2fs_sb_info *sbi) { return (struct dirty_seglist_info *)(SM_I(sbi)->dirty_info); } static inline struct address_space *META_MAPPING(struct f2fs_sb_info *sbi) { return sbi->meta_inode->i_mapping; } static inline struct address_space *NODE_MAPPING(struct f2fs_sb_info *sbi) { return sbi->node_inode->i_mapping; } static inline bool is_sbi_flag_set(struct f2fs_sb_info *sbi, unsigned int type) { return test_bit(type, &sbi->s_flag); } static inline void set_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { set_bit(type, &sbi->s_flag); } static inline void clear_sbi_flag(struct f2fs_sb_info *sbi, unsigned int type) { clear_bit(type, &sbi->s_flag); } static inline unsigned long long cur_cp_version(struct f2fs_checkpoint *cp) { return le64_to_cpu(cp->checkpoint_ver); } static inline unsigned long f2fs_qf_ino(struct super_block *sb, int type) { if (type < F2FS_MAX_QUOTAS) return le32_to_cpu(F2FS_SB(sb)->raw_super->qf_ino[type]); return 0; } static inline __u64 cur_cp_crc(struct f2fs_checkpoint *cp) { size_t crc_offset = le32_to_cpu(cp->checksum_offset); return le32_to_cpu(*((__le32 *)((unsigned char *)cp + crc_offset))); } static inline bool __is_set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags = le32_to_cpu(cp->ckpt_flags); return ckpt_flags & f; } static inline bool is_set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { return __is_set_ckpt_flags(F2FS_CKPT(sbi), f); } static inline void __set_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags |= f; cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void set_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __set_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void __clear_ckpt_flags(struct f2fs_checkpoint *cp, unsigned int f) { unsigned int ckpt_flags; ckpt_flags = le32_to_cpu(cp->ckpt_flags); ckpt_flags &= (~f); cp->ckpt_flags = cpu_to_le32(ckpt_flags); } static inline void clear_ckpt_flags(struct f2fs_sb_info *sbi, unsigned int f) { unsigned long flags; spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), f); spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline void disable_nat_bits(struct f2fs_sb_info *sbi, bool lock) { unsigned long flags; /* * In order to re-enable nat_bits we need to call fsck.f2fs by * set_sbi_flag(sbi, SBI_NEED_FSCK). But it may give huge cost, * so let's rely on regular fsck or unclean shutdown. */ if (lock) spin_lock_irqsave(&sbi->cp_lock, flags); __clear_ckpt_flags(F2FS_CKPT(sbi), CP_NAT_BITS_FLAG); kvfree(NM_I(sbi)->nat_bits); NM_I(sbi)->nat_bits = NULL; if (lock) spin_unlock_irqrestore(&sbi->cp_lock, flags); } static inline bool enabled_nat_bits(struct f2fs_sb_info *sbi, struct cp_control *cpc) { bool set = is_set_ckpt_flags(sbi, CP_NAT_BITS_FLAG); return (cpc) ? (cpc->reason & CP_UMOUNT) && set : set; } static inline void f2fs_lock_op(struct f2fs_sb_info *sbi) { down_read(&sbi->cp_rwsem); } static inline int f2fs_trylock_op(struct f2fs_sb_info *sbi) { return down_read_trylock(&sbi->cp_rwsem); } static inline void f2fs_unlock_op(struct f2fs_sb_info *sbi) { up_read(&sbi->cp_rwsem); } static inline void f2fs_lock_all(struct f2fs_sb_info *sbi) { down_write(&sbi->cp_rwsem); } static inline void f2fs_unlock_all(struct f2fs_sb_info *sbi) { up_write(&sbi->cp_rwsem); } static inline int __get_cp_reason(struct f2fs_sb_info *sbi) { int reason = CP_SYNC; if (test_opt(sbi, FASTBOOT)) reason = CP_FASTBOOT; if (is_sbi_flag_set(sbi, SBI_IS_CLOSE)) reason = CP_UMOUNT; return reason; } static inline bool __remain_node_summaries(int reason) { return (reason & (CP_UMOUNT | CP_FASTBOOT)); } static inline bool __exist_node_summaries(struct f2fs_sb_info *sbi) { return (is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG) || is_set_ckpt_flags(sbi, CP_FASTBOOT_FLAG)); } /* * Check whether the inode has blocks or not */ static inline int F2FS_HAS_BLOCKS(struct inode *inode) { block_t xattr_block = F2FS_I(inode)->i_xattr_nid ? 1 : 0; return (inode->i_blocks >> F2FS_LOG_SECTORS_PER_BLOCK) > xattr_block; } static inline bool f2fs_has_xattr_block(unsigned int ofs) { return ofs == XATTR_NODE_OFFSET; } static inline bool __allow_reserved_blocks(struct f2fs_sb_info *sbi, struct inode *inode, bool cap) { if (!inode) return true; if (!test_opt(sbi, RESERVE_ROOT)) return false; if (IS_NOQUOTA(inode)) return true; if (uid_eq(F2FS_OPTION(sbi).s_resuid, current_fsuid())) return true; if (!gid_eq(F2FS_OPTION(sbi).s_resgid, GLOBAL_ROOT_GID) && in_group_p(F2FS_OPTION(sbi).s_resgid)) return true; if (cap && capable(CAP_SYS_RESOURCE)) return true; return false; } static inline void f2fs_i_blocks_write(struct inode *, block_t, bool, bool); static inline int inc_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, blkcnt_t *count) { blkcnt_t diff = 0, release = 0; block_t avail_user_block_count; int ret; ret = dquot_reserve_block(inode, *count); if (ret) return ret; if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); release = *count; goto enospc; } /* * let's increase this in prior to actual block count change in order * for f2fs_sync_file to avoid data races when deciding checkpoint. */ percpu_counter_add(&sbi->alloc_valid_block_count, (*count)); spin_lock(&sbi->stat_lock); sbi->total_valid_block_count += (block_t)(*count); avail_user_block_count = sbi->user_block_count - sbi->current_reserved_blocks; if (!__allow_reserved_blocks(sbi, inode, true)) avail_user_block_count -= F2FS_OPTION(sbi).root_reserved_blocks; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) { if (avail_user_block_count > sbi->unusable_block_count) avail_user_block_count -= sbi->unusable_block_count; else avail_user_block_count = 0; } if (unlikely(sbi->total_valid_block_count > avail_user_block_count)) { diff = sbi->total_valid_block_count - avail_user_block_count; if (diff > *count) diff = *count; *count -= diff; release = diff; sbi->total_valid_block_count -= diff; if (!*count) { spin_unlock(&sbi->stat_lock); goto enospc; } } spin_unlock(&sbi->stat_lock); if (unlikely(release)) { percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); } f2fs_i_blocks_write(inode, *count, true, true); return 0; enospc: percpu_counter_sub(&sbi->alloc_valid_block_count, release); dquot_release_reservation_block(inode, release); return -ENOSPC; } __printf(2, 3) void f2fs_printk(struct f2fs_sb_info *sbi, const char *fmt, ...); #define f2fs_err(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_ERR fmt, ##__VA_ARGS__) #define f2fs_warn(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_WARNING fmt, ##__VA_ARGS__) #define f2fs_notice(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_NOTICE fmt, ##__VA_ARGS__) #define f2fs_info(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_INFO fmt, ##__VA_ARGS__) #define f2fs_debug(sbi, fmt, ...) \ f2fs_printk(sbi, KERN_DEBUG fmt, ##__VA_ARGS__) static inline void dec_valid_block_count(struct f2fs_sb_info *sbi, struct inode *inode, block_t count) { blkcnt_t sectors = count << F2FS_LOG_SECTORS_PER_BLOCK; spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, sbi->total_valid_block_count < (block_t) count); sbi->total_valid_block_count -= (block_t)count; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks = min(sbi->reserved_blocks, sbi->current_reserved_blocks + count); spin_unlock(&sbi->stat_lock); if (unlikely(inode->i_blocks < sectors)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu, sectors:%llu", inode->i_ino, (unsigned long long)inode->i_blocks, (unsigned long long)sectors); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, count, false, true); } static inline void inc_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_inc(&sbi->nr_pages[count_type]); if (count_type == F2FS_DIRTY_DENTS || count_type == F2FS_DIRTY_NODES || count_type == F2FS_DIRTY_META || count_type == F2FS_DIRTY_QDATA || count_type == F2FS_DIRTY_IMETA) set_sbi_flag(sbi, SBI_IS_DIRTY); } static inline void inode_inc_dirty_pages(struct inode *inode) { atomic_inc(&F2FS_I(inode)->dirty_pages); inc_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) inc_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline void dec_page_count(struct f2fs_sb_info *sbi, int count_type) { atomic_dec(&sbi->nr_pages[count_type]); } static inline void inode_dec_dirty_pages(struct inode *inode) { if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) && !S_ISLNK(inode->i_mode)) return; atomic_dec(&F2FS_I(inode)->dirty_pages); dec_page_count(F2FS_I_SB(inode), S_ISDIR(inode->i_mode) ? F2FS_DIRTY_DENTS : F2FS_DIRTY_DATA); if (IS_NOQUOTA(inode)) dec_page_count(F2FS_I_SB(inode), F2FS_DIRTY_QDATA); } static inline s64 get_pages(struct f2fs_sb_info *sbi, int count_type) { return atomic_read(&sbi->nr_pages[count_type]); } static inline int get_dirty_pages(struct inode *inode) { return atomic_read(&F2FS_I(inode)->dirty_pages); } static inline int get_blocktype_secs(struct f2fs_sb_info *sbi, int block_type) { unsigned int pages_per_sec = sbi->segs_per_sec * sbi->blocks_per_seg; unsigned int segs = (get_pages(sbi, block_type) + pages_per_sec - 1) >> sbi->log_blocks_per_seg; return segs / sbi->segs_per_sec; } static inline block_t valid_user_blocks(struct f2fs_sb_info *sbi) { return sbi->total_valid_block_count; } static inline block_t discard_blocks(struct f2fs_sb_info *sbi) { return sbi->discard_blks; } static inline unsigned long __bitmap_size(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); /* return NAT or SIT bitmap */ if (flag == NAT_BITMAP) return le32_to_cpu(ckpt->nat_ver_bitmap_bytesize); else if (flag == SIT_BITMAP) return le32_to_cpu(ckpt->sit_ver_bitmap_bytesize); return 0; } static inline block_t __cp_payload(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_payload); } static inline void *__bitmap_ptr(struct f2fs_sb_info *sbi, int flag) { struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); int offset; if (is_set_ckpt_flags(sbi, CP_LARGE_NAT_BITMAP_FLAG)) { offset = (flag == SIT_BITMAP) ? le32_to_cpu(ckpt->nat_ver_bitmap_bytesize) : 0; /* * if large_nat_bitmap feature is enabled, leave checksum * protection for all nat/sit bitmaps. */ return &ckpt->sit_nat_version_bitmap + offset + sizeof(__le32); } if (__cp_payload(sbi) > 0) { if (flag == NAT_BITMAP) return &ckpt->sit_nat_version_bitmap; else return (unsigned char *)ckpt + F2FS_BLKSIZE; } else { offset = (flag == NAT_BITMAP) ? le32_to_cpu(ckpt->sit_ver_bitmap_bytesize) : 0; return &ckpt->sit_nat_version_bitmap + offset; } } static inline block_t __start_cp_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 2) start_addr += sbi->blocks_per_seg; return start_addr; } static inline block_t __start_cp_next_addr(struct f2fs_sb_info *sbi) { block_t start_addr = le32_to_cpu(F2FS_RAW_SUPER(sbi)->cp_blkaddr); if (sbi->cur_cp_pack == 1) start_addr += sbi->blocks_per_seg; return start_addr; } static inline void __set_cp_next_pack(struct f2fs_sb_info *sbi) { sbi->cur_cp_pack = (sbi->cur_cp_pack == 1) ? 2 : 1; } static inline block_t __start_sum_addr(struct f2fs_sb_info *sbi) { return le32_to_cpu(F2FS_CKPT(sbi)->cp_pack_start_sum); } static inline int inc_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { block_t valid_block_count; unsigned int valid_node_count, user_block_count; int err; if (is_inode) { if (inode) { err = dquot_alloc_inode(inode); if (err) return err; } } else { err = dquot_reserve_block(inode, 1); if (err) return err; } if (time_to_inject(sbi, FAULT_BLOCK)) { f2fs_show_injection_info(FAULT_BLOCK); goto enospc; } spin_lock(&sbi->stat_lock); valid_block_count = sbi->total_valid_block_count + sbi->current_reserved_blocks + 1; if (!__allow_reserved_blocks(sbi, inode, false)) valid_block_count += F2FS_OPTION(sbi).root_reserved_blocks; user_block_count = sbi->user_block_count; if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) user_block_count -= sbi->unusable_block_count; if (unlikely(valid_block_count > user_block_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } valid_node_count = sbi->total_valid_node_count + 1; if (unlikely(valid_node_count > sbi->total_node_count)) { spin_unlock(&sbi->stat_lock); goto enospc; } sbi->total_valid_node_count++; sbi->total_valid_block_count++; spin_unlock(&sbi->stat_lock); if (inode) { if (is_inode) f2fs_mark_inode_dirty_sync(inode, true); else f2fs_i_blocks_write(inode, 1, true, true); } percpu_counter_inc(&sbi->alloc_valid_block_count); return 0; enospc: if (is_inode) { if (inode) dquot_free_inode(inode); } else { dquot_release_reservation_block(inode, 1); } return -ENOSPC; } static inline void dec_valid_node_count(struct f2fs_sb_info *sbi, struct inode *inode, bool is_inode) { spin_lock(&sbi->stat_lock); f2fs_bug_on(sbi, !sbi->total_valid_block_count); f2fs_bug_on(sbi, !sbi->total_valid_node_count); sbi->total_valid_node_count--; sbi->total_valid_block_count--; if (sbi->reserved_blocks && sbi->current_reserved_blocks < sbi->reserved_blocks) sbi->current_reserved_blocks++; spin_unlock(&sbi->stat_lock); if (is_inode) { dquot_free_inode(inode); } else { if (unlikely(inode->i_blocks == 0)) { f2fs_warn(sbi, "Inconsistent i_blocks, ino:%lu, iblocks:%llu", inode->i_ino, (unsigned long long)inode->i_blocks); set_sbi_flag(sbi, SBI_NEED_FSCK); return; } f2fs_i_blocks_write(inode, 1, false, true); } } static inline unsigned int valid_node_count(struct f2fs_sb_info *sbi) { return sbi->total_valid_node_count; } static inline void inc_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_inc(&sbi->total_valid_inode_count); } static inline void dec_valid_inode_count(struct f2fs_sb_info *sbi) { percpu_counter_dec(&sbi->total_valid_inode_count); } static inline s64 valid_inode_count(struct f2fs_sb_info *sbi) { return percpu_counter_sum_positive(&sbi->total_valid_inode_count); } static inline struct page *f2fs_grab_cache_page(struct address_space *mapping, pgoff_t index, bool for_write) { struct page *page; if (IS_ENABLED(CONFIG_F2FS_FAULT_INJECTION)) { if (!for_write) page = find_get_page_flags(mapping, index, FGP_LOCK | FGP_ACCESSED); else page = find_lock_page(mapping, index); if (page) return page; if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_ALLOC)) { f2fs_show_injection_info(FAULT_PAGE_ALLOC); return NULL; } } if (!for_write) return grab_cache_page(mapping, index); return grab_cache_page_write_begin(mapping, index, AOP_FLAG_NOFS); } static inline struct page *f2fs_pagecache_get_page( struct address_space *mapping, pgoff_t index, int fgp_flags, gfp_t gfp_mask) { if (time_to_inject(F2FS_M_SB(mapping), FAULT_PAGE_GET)) { f2fs_show_injection_info(FAULT_PAGE_GET); return NULL; } return pagecache_get_page(mapping, index, fgp_flags, gfp_mask); } static inline void f2fs_copy_page(struct page *src, struct page *dst) { char *src_kaddr = kmap(src); char *dst_kaddr = kmap(dst); memcpy(dst_kaddr, src_kaddr, PAGE_SIZE); kunmap(dst); kunmap(src); } static inline void f2fs_put_page(struct page *page, int unlock) { if (!page) return; if (unlock) { f2fs_bug_on(F2FS_P_SB(page), !PageLocked(page)); unlock_page(page); } put_page(page); } static inline void f2fs_put_dnode(struct dnode_of_data *dn) { if (dn->node_page) f2fs_put_page(dn->node_page, 1); if (dn->inode_page && dn->node_page != dn->inode_page) f2fs_put_page(dn->inode_page, 0); dn->node_page = NULL; dn->inode_page = NULL; } static inline struct kmem_cache *f2fs_kmem_cache_create(const char *name, size_t size) { return kmem_cache_create(name, size, 0, SLAB_RECLAIM_ACCOUNT, NULL); } static inline void *f2fs_kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags) { void *entry; entry = kmem_cache_alloc(cachep, flags); if (!entry) entry = kmem_cache_alloc(cachep, flags | __GFP_NOFAIL); return entry; } static inline struct bio *f2fs_bio_alloc(struct f2fs_sb_info *sbi, int npages, bool no_fail) { struct bio *bio; if (no_fail) { /* No failure on bio allocation */ bio = bio_alloc(GFP_NOIO, npages); if (!bio) bio = bio_alloc(GFP_NOIO | __GFP_NOFAIL, npages); return bio; } if (time_to_inject(sbi, FAULT_ALLOC_BIO)) { f2fs_show_injection_info(FAULT_ALLOC_BIO); return NULL; } return bio_alloc(GFP_KERNEL, npages); } static inline bool is_idle(struct f2fs_sb_info *sbi, int type) { if (sbi->gc_mode == GC_URGENT) return true; if (get_pages(sbi, F2FS_RD_DATA) || get_pages(sbi, F2FS_RD_NODE) || get_pages(sbi, F2FS_RD_META) || get_pages(sbi, F2FS_WB_DATA) || get_pages(sbi, F2FS_WB_CP_DATA) || get_pages(sbi, F2FS_DIO_READ) || get_pages(sbi, F2FS_DIO_WRITE)) return false; if (type != DISCARD_TIME && SM_I(sbi) && SM_I(sbi)->dcc_info && atomic_read(&SM_I(sbi)->dcc_info->queued_discard)) return false; if (SM_I(sbi) && SM_I(sbi)->fcc_info && atomic_read(&SM_I(sbi)->fcc_info->queued_flush)) return false; return f2fs_time_over(sbi, type); } static inline void f2fs_radix_tree_insert(struct radix_tree_root *root, unsigned long index, void *item) { while (radix_tree_insert(root, index, item)) cond_resched(); } #define RAW_IS_INODE(p) ((p)->footer.nid == (p)->footer.ino) static inline bool IS_INODE(struct page *page) { struct f2fs_node *p = F2FS_NODE(page); return RAW_IS_INODE(p); } static inline int offset_in_addr(struct f2fs_inode *i) { return (i->i_inline & F2FS_EXTRA_ATTR) ? (le16_to_cpu(i->i_extra_isize) / sizeof(__le32)) : 0; } static inline __le32 *blkaddr_in_node(struct f2fs_node *node) { return RAW_IS_INODE(node) ? node->i.i_addr : node->dn.addr; } static inline int f2fs_has_extra_attr(struct inode *inode); static inline block_t datablock_addr(struct inode *inode, struct page *node_page, unsigned int offset) { struct f2fs_node *raw_node; __le32 *addr_array; int base = 0; bool is_inode = IS_INODE(node_page); raw_node = F2FS_NODE(node_page); /* from GC path only */ if (is_inode) { if (!inode) base = offset_in_addr(&raw_node->i); else if (f2fs_has_extra_attr(inode)) base = get_extra_isize(inode); } addr_array = blkaddr_in_node(raw_node); return le32_to_cpu(addr_array[base + offset]); } static inline int f2fs_test_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); return mask & *addr; } static inline void f2fs_set_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr |= mask; } static inline void f2fs_clear_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr &= ~mask; } static inline int f2fs_test_and_set_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr |= mask; return ret; } static inline int f2fs_test_and_clear_bit(unsigned int nr, char *addr) { int mask; int ret; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); ret = mask & *addr; *addr &= ~mask; return ret; } static inline void f2fs_change_bit(unsigned int nr, char *addr) { int mask; addr += (nr >> 3); mask = 1 << (7 - (nr & 0x07)); *addr ^= mask; } /* * On-disk inode flags (f2fs_inode::i_flags) */ #define F2FS_SYNC_FL 0x00000008 /* Synchronous updates */ #define F2FS_IMMUTABLE_FL 0x00000010 /* Immutable file */ #define F2FS_APPEND_FL 0x00000020 /* writes to file may only append */ #define F2FS_NODUMP_FL 0x00000040 /* do not dump file */ #define F2FS_NOATIME_FL 0x00000080 /* do not update atime */ #define F2FS_INDEX_FL 0x00001000 /* hash-indexed directory */ #define F2FS_DIRSYNC_FL 0x00010000 /* dirsync behaviour (directories only) */ #define F2FS_PROJINHERIT_FL 0x20000000 /* Create with parents projid */ /* Flags that should be inherited by new inodes from their parent. */ #define F2FS_FL_INHERITED (F2FS_SYNC_FL | F2FS_NODUMP_FL | F2FS_NOATIME_FL | \ F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL) /* Flags that are appropriate for regular files (all but dir-specific ones). */ #define F2FS_REG_FLMASK (~(F2FS_DIRSYNC_FL | F2FS_PROJINHERIT_FL)) /* Flags that are appropriate for non-directories/regular files. */ #define F2FS_OTHER_FLMASK (F2FS_NODUMP_FL | F2FS_NOATIME_FL) static inline __u32 f2fs_mask_flags(umode_t mode, __u32 flags) { if (S_ISDIR(mode)) return flags; else if (S_ISREG(mode)) return flags & F2FS_REG_FLMASK; else return flags & F2FS_OTHER_FLMASK; } /* used for f2fs_inode_info->flags */ enum { FI_NEW_INODE, /* indicate newly allocated inode */ FI_DIRTY_INODE, /* indicate inode is dirty or not */ FI_AUTO_RECOVER, /* indicate inode is recoverable */ FI_DIRTY_DIR, /* indicate directory has dirty pages */ FI_INC_LINK, /* need to increment i_nlink */ FI_ACL_MODE, /* indicate acl mode */ FI_NO_ALLOC, /* should not allocate any blocks */ FI_FREE_NID, /* free allocated nide */ FI_NO_EXTENT, /* not to use the extent cache */ FI_INLINE_XATTR, /* used for inline xattr */ FI_INLINE_DATA, /* used for inline data*/ FI_INLINE_DENTRY, /* used for inline dentry */ FI_APPEND_WRITE, /* inode has appended data */ FI_UPDATE_WRITE, /* inode has in-place-update data */ FI_NEED_IPU, /* used for ipu per file */ FI_ATOMIC_FILE, /* indicate atomic file */ FI_ATOMIC_COMMIT, /* indicate the state of atomical committing */ FI_VOLATILE_FILE, /* indicate volatile file */ FI_FIRST_BLOCK_WRITTEN, /* indicate #0 data block was written */ FI_DROP_CACHE, /* drop dirty page cache */ FI_DATA_EXIST, /* indicate data exists */ FI_INLINE_DOTS, /* indicate inline dot dentries */ FI_DO_DEFRAG, /* indicate defragment is running */ FI_DIRTY_FILE, /* indicate regular/symlink has dirty pages */ FI_NO_PREALLOC, /* indicate skipped preallocated blocks */ FI_HOT_DATA, /* indicate file is hot */ FI_EXTRA_ATTR, /* indicate file has extra attribute */ FI_PROJ_INHERIT, /* indicate file inherits projectid */ FI_PIN_FILE, /* indicate file should not be gced */ FI_ATOMIC_REVOKE_REQUEST, /* request to drop atomic data */ }; static inline void __mark_inode_dirty_flag(struct inode *inode, int flag, bool set) { switch (flag) { case FI_INLINE_XATTR: case FI_INLINE_DATA: case FI_INLINE_DENTRY: case FI_NEW_INODE: if (set) return; /* fall through */ case FI_DATA_EXIST: case FI_INLINE_DOTS: case FI_PIN_FILE: f2fs_mark_inode_dirty_sync(inode, true); } } static inline void set_inode_flag(struct inode *inode, int flag) { if (!test_bit(flag, &F2FS_I(inode)->flags)) set_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, true); } static inline int is_inode_flag_set(struct inode *inode, int flag) { return test_bit(flag, &F2FS_I(inode)->flags); } static inline void clear_inode_flag(struct inode *inode, int flag) { if (test_bit(flag, &F2FS_I(inode)->flags)) clear_bit(flag, &F2FS_I(inode)->flags); __mark_inode_dirty_flag(inode, flag, false); } static inline void set_acl_inode(struct inode *inode, umode_t mode) { F2FS_I(inode)->i_acl_mode = mode; set_inode_flag(inode, FI_ACL_MODE); f2fs_mark_inode_dirty_sync(inode, false); } static inline void f2fs_i_links_write(struct inode *inode, bool inc) { if (inc) inc_nlink(inode); else drop_nlink(inode); f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_blocks_write(struct inode *inode, block_t diff, bool add, bool claim) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); /* add = 1, claim = 1 should be dquot_reserve_block in pair */ if (add) { if (claim) dquot_claim_block(inode, diff); else dquot_alloc_block_nofail(inode, diff); } else { dquot_free_block(inode, diff); } f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_size_write(struct inode *inode, loff_t i_size) { bool clean = !is_inode_flag_set(inode, FI_DIRTY_INODE); bool recover = is_inode_flag_set(inode, FI_AUTO_RECOVER); if (i_size_read(inode) == i_size) return; i_size_write(inode, i_size); f2fs_mark_inode_dirty_sync(inode, true); if (clean || recover) set_inode_flag(inode, FI_AUTO_RECOVER); } static inline void f2fs_i_depth_write(struct inode *inode, unsigned int depth) { F2FS_I(inode)->i_current_depth = depth; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_gc_failures_write(struct inode *inode, unsigned int count) { F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN] = count; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_xnid_write(struct inode *inode, nid_t xnid) { F2FS_I(inode)->i_xattr_nid = xnid; f2fs_mark_inode_dirty_sync(inode, true); } static inline void f2fs_i_pino_write(struct inode *inode, nid_t pino) { F2FS_I(inode)->i_pino = pino; f2fs_mark_inode_dirty_sync(inode, true); } static inline void get_inline_info(struct inode *inode, struct f2fs_inode *ri) { struct f2fs_inode_info *fi = F2FS_I(inode); if (ri->i_inline & F2FS_INLINE_XATTR) set_bit(FI_INLINE_XATTR, &fi->flags); if (ri->i_inline & F2FS_INLINE_DATA) set_bit(FI_INLINE_DATA, &fi->flags); if (ri->i_inline & F2FS_INLINE_DENTRY) set_bit(FI_INLINE_DENTRY, &fi->flags); if (ri->i_inline & F2FS_DATA_EXIST) set_bit(FI_DATA_EXIST, &fi->flags); if (ri->i_inline & F2FS_INLINE_DOTS) set_bit(FI_INLINE_DOTS, &fi->flags); if (ri->i_inline & F2FS_EXTRA_ATTR) set_bit(FI_EXTRA_ATTR, &fi->flags); if (ri->i_inline & F2FS_PIN_FILE) set_bit(FI_PIN_FILE, &fi->flags); } static inline void set_raw_inline(struct inode *inode, struct f2fs_inode *ri) { ri->i_inline = 0; if (is_inode_flag_set(inode, FI_INLINE_XATTR)) ri->i_inline |= F2FS_INLINE_XATTR; if (is_inode_flag_set(inode, FI_INLINE_DATA)) ri->i_inline |= F2FS_INLINE_DATA; if (is_inode_flag_set(inode, FI_INLINE_DENTRY)) ri->i_inline |= F2FS_INLINE_DENTRY; if (is_inode_flag_set(inode, FI_DATA_EXIST)) ri->i_inline |= F2FS_DATA_EXIST; if (is_inode_flag_set(inode, FI_INLINE_DOTS)) ri->i_inline |= F2FS_INLINE_DOTS; if (is_inode_flag_set(inode, FI_EXTRA_ATTR)) ri->i_inline |= F2FS_EXTRA_ATTR; if (is_inode_flag_set(inode, FI_PIN_FILE)) ri->i_inline |= F2FS_PIN_FILE; } static inline int f2fs_has_extra_attr(struct inode *inode) { return is_inode_flag_set(inode, FI_EXTRA_ATTR); } static inline int f2fs_has_inline_xattr(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_XATTR); } static inline unsigned int addrs_per_inode(struct inode *inode) { unsigned int addrs = CUR_ADDRS_PER_INODE(inode) - get_inline_xattr_addrs(inode); return ALIGN_DOWN(addrs, 1); } static inline unsigned int addrs_per_block(struct inode *inode) { return ALIGN_DOWN(DEF_ADDRS_PER_BLOCK, 1); } static inline void *inline_xattr_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); return (void *)&(ri->i_addr[DEF_ADDRS_PER_INODE - get_inline_xattr_addrs(inode)]); } static inline int inline_xattr_size(struct inode *inode) { if (f2fs_has_inline_xattr(inode)) return get_inline_xattr_addrs(inode) * sizeof(__le32); return 0; } static inline int f2fs_has_inline_data(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DATA); } static inline int f2fs_exist_data(struct inode *inode) { return is_inode_flag_set(inode, FI_DATA_EXIST); } static inline int f2fs_has_inline_dots(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DOTS); } static inline bool f2fs_is_pinned_file(struct inode *inode) { return is_inode_flag_set(inode, FI_PIN_FILE); } static inline bool f2fs_is_atomic_file(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_FILE); } static inline bool f2fs_is_commit_atomic_write(struct inode *inode) { return is_inode_flag_set(inode, FI_ATOMIC_COMMIT); } static inline bool f2fs_is_volatile_file(struct inode *inode) { return is_inode_flag_set(inode, FI_VOLATILE_FILE); } static inline bool f2fs_is_first_block_written(struct inode *inode) { return is_inode_flag_set(inode, FI_FIRST_BLOCK_WRITTEN); } static inline bool f2fs_is_drop_cache(struct inode *inode) { return is_inode_flag_set(inode, FI_DROP_CACHE); } static inline void *inline_data_addr(struct inode *inode, struct page *page) { struct f2fs_inode *ri = F2FS_INODE(page); int extra_size = get_extra_isize(inode); return (void *)&(ri->i_addr[extra_size + DEF_INLINE_RESERVED_SIZE]); } static inline int f2fs_has_inline_dentry(struct inode *inode) { return is_inode_flag_set(inode, FI_INLINE_DENTRY); } static inline int is_file(struct inode *inode, int type) { return F2FS_I(inode)->i_advise & type; } static inline void set_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise |= type; f2fs_mark_inode_dirty_sync(inode, true); } static inline void clear_file(struct inode *inode, int type) { F2FS_I(inode)->i_advise &= ~type; f2fs_mark_inode_dirty_sync(inode, true); } static inline bool f2fs_skip_inode_update(struct inode *inode, int dsync) { bool ret; if (dsync) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); spin_lock(&sbi->inode_lock[DIRTY_META]); ret = list_empty(&F2FS_I(inode)->gdirty_list); spin_unlock(&sbi->inode_lock[DIRTY_META]); return ret; } if (!is_inode_flag_set(inode, FI_AUTO_RECOVER) || file_keep_isize(inode) || i_size_read(inode) & ~PAGE_MASK) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time, &inode->i_atime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 1, &inode->i_ctime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 2, &inode->i_mtime)) return false; if (!timespec64_equal(F2FS_I(inode)->i_disk_time + 3, &F2FS_I(inode)->i_crtime)) return false; down_read(&F2FS_I(inode)->i_sem); ret = F2FS_I(inode)->last_disk_size == i_size_read(inode); up_read(&F2FS_I(inode)->i_sem); return ret; } static inline bool f2fs_readonly(struct super_block *sb) { return sb_rdonly(sb); } static inline bool f2fs_cp_error(struct f2fs_sb_info *sbi) { return is_set_ckpt_flags(sbi, CP_ERROR_FLAG); } static inline bool is_dot_dotdot(const struct qstr *str) { if (str->len == 1 && str->name[0] == '.') return true; if (str->len == 2 && str->name[0] == '.' && str->name[1] == '.') return true; return false; } static inline bool f2fs_may_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (!test_opt(sbi, EXTENT_CACHE) || is_inode_flag_set(inode, FI_NO_EXTENT)) return false; /* * for recovered files during mount do not create extents * if shrinker is not registered. */ if (list_empty(&sbi->s_list)) return false; return S_ISREG(inode->i_mode); } static inline void *f2fs_kmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { void *ret; if (time_to_inject(sbi, FAULT_KMALLOC)) { f2fs_show_injection_info(FAULT_KMALLOC); return NULL; } ret = kmalloc(size, flags); if (ret) return ret; return kvmalloc(size, flags); } static inline void *f2fs_kzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kmalloc(sbi, size, flags | __GFP_ZERO); } static inline void *f2fs_kvmalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { if (time_to_inject(sbi, FAULT_KVMALLOC)) { f2fs_show_injection_info(FAULT_KVMALLOC); return NULL; } return kvmalloc(size, flags); } static inline void *f2fs_kvzalloc(struct f2fs_sb_info *sbi, size_t size, gfp_t flags) { return f2fs_kvmalloc(sbi, size, flags | __GFP_ZERO); } static inline int get_extra_isize(struct inode *inode) { return F2FS_I(inode)->i_extra_isize / sizeof(__le32); } static inline int get_inline_xattr_addrs(struct inode *inode) { return F2FS_I(inode)->i_inline_xattr_size; } #define f2fs_get_inode_mode(i) \ ((is_inode_flag_set(i, FI_ACL_MODE)) ? \ (F2FS_I(i)->i_acl_mode) : ((i)->i_mode)) #define F2FS_TOTAL_EXTRA_ATTR_SIZE \ (offsetof(struct f2fs_inode, i_extra_end) - \ offsetof(struct f2fs_inode, i_extra_isize)) \ #define F2FS_OLD_ATTRIBUTE_SIZE (offsetof(struct f2fs_inode, i_addr)) #define F2FS_FITS_IN_INODE(f2fs_inode, extra_isize, field) \ ((offsetof(typeof(*(f2fs_inode)), field) + \ sizeof((f2fs_inode)->field)) \ <= (F2FS_OLD_ATTRIBUTE_SIZE + (extra_isize))) \ static inline void f2fs_reset_iostat(struct f2fs_sb_info *sbi) { int i; spin_lock(&sbi->iostat_lock); for (i = 0; i < NR_IO_TYPE; i++) sbi->write_iostat[i] = 0; spin_unlock(&sbi->iostat_lock); } static inline void f2fs_update_iostat(struct f2fs_sb_info *sbi, enum iostat_type type, unsigned long long io_bytes) { if (!sbi->iostat_enable) return; spin_lock(&sbi->iostat_lock); sbi->write_iostat[type] += io_bytes; if (type == APP_WRITE_IO || type == APP_DIRECT_IO) sbi->write_iostat[APP_BUFFERED_IO] = sbi->write_iostat[APP_WRITE_IO] - sbi->write_iostat[APP_DIRECT_IO]; spin_unlock(&sbi->iostat_lock); } #define __is_large_section(sbi) ((sbi)->segs_per_sec > 1) #define __is_meta_io(fio) (PAGE_TYPE_OF_BIO((fio)->type) == META) bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); static inline void verify_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type) { if (!f2fs_is_valid_blkaddr(sbi, blkaddr, type)) { f2fs_err(sbi, "invalid blkaddr: %u, type: %d, run fsck to fix.", blkaddr, type); f2fs_bug_on(sbi, 1); } } static inline bool __is_valid_data_blkaddr(block_t blkaddr) { if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR) return false; return true; } static inline void f2fs_set_page_private(struct page *page, unsigned long data) { if (PagePrivate(page)) return; get_page(page); SetPagePrivate(page); set_page_private(page, data); } static inline void f2fs_clear_page_private(struct page *page) { if (!PagePrivate(page)) return; set_page_private(page, 0); ClearPagePrivate(page); f2fs_put_page(page, 0); } /* * file.c */ int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync); void f2fs_truncate_data_blocks(struct dnode_of_data *dn); int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock); int f2fs_truncate(struct inode *inode); int f2fs_getattr(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int flags); int f2fs_setattr(struct dentry *dentry, struct iattr *attr); int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end); void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count); int f2fs_precache_extents(struct inode *inode); long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg); long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg); int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid); int f2fs_pin_file_control(struct inode *inode, bool inc); /* * inode.c */ void f2fs_set_inode_flags(struct inode *inode); bool f2fs_inode_chksum_verify(struct f2fs_sb_info *sbi, struct page *page); void f2fs_inode_chksum_set(struct f2fs_sb_info *sbi, struct page *page); struct inode *f2fs_iget(struct super_block *sb, unsigned long ino); struct inode *f2fs_iget_retry(struct super_block *sb, unsigned long ino); int f2fs_try_to_free_nats(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_update_inode(struct inode *inode, struct page *node_page); void f2fs_update_inode_page(struct inode *inode); int f2fs_write_inode(struct inode *inode, struct writeback_control *wbc); void f2fs_evict_inode(struct inode *inode); void f2fs_handle_failed_inode(struct inode *inode); /* * namei.c */ int f2fs_update_extension_list(struct f2fs_sb_info *sbi, const char *name, bool hot, bool set); struct dentry *f2fs_get_parent(struct dentry *child); /* * dir.c */ unsigned char f2fs_get_de_type(struct f2fs_dir_entry *de); struct f2fs_dir_entry *f2fs_find_target_dentry(struct fscrypt_name *fname, f2fs_hash_t namehash, int *max_slots, struct f2fs_dentry_ptr *d); int f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d, unsigned int start_pos, struct fscrypt_str *fstr); void f2fs_do_make_empty_dir(struct inode *inode, struct inode *parent, struct f2fs_dentry_ptr *d); struct page *f2fs_init_inode_metadata(struct inode *inode, struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct page *dpage); void f2fs_update_parent_metadata(struct inode *dir, struct inode *inode, unsigned int current_depth); int f2fs_room_for_filename(const void *bitmap, int slots, int max_slots); void f2fs_drop_nlink(struct inode *dir, struct inode *inode); struct f2fs_dir_entry *__f2fs_find_entry(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir, const struct qstr *child, struct page **res_page); struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p); ino_t f2fs_inode_by_name(struct inode *dir, const struct qstr *qstr, struct page **page); void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de, struct page *page, struct inode *inode); void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d, const struct qstr *name, f2fs_hash_t name_hash, unsigned int bit_pos); int f2fs_add_regular_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); int f2fs_add_dentry(struct inode *dir, struct fscrypt_name *fname, struct inode *inode, nid_t ino, umode_t mode); int f2fs_do_add_link(struct inode *dir, const struct qstr *name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); int f2fs_do_tmpfile(struct inode *inode, struct inode *dir); bool f2fs_empty_dir(struct inode *dir); static inline int f2fs_add_link(struct dentry *dentry, struct inode *inode) { return f2fs_do_add_link(d_inode(dentry->d_parent), &dentry->d_name, inode, inode->i_ino, inode->i_mode); } /* * super.c */ int f2fs_inode_dirtied(struct inode *inode, bool sync); void f2fs_inode_synced(struct inode *inode); int f2fs_enable_quota_files(struct f2fs_sb_info *sbi, bool rdonly); int f2fs_quota_sync(struct super_block *sb, int type); void f2fs_quota_off_umount(struct super_block *sb); int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover); int f2fs_sync_fs(struct super_block *sb, int sync); int f2fs_sanity_check_ckpt(struct f2fs_sb_info *sbi); /* * hash.c */ f2fs_hash_t f2fs_dentry_hash(const struct qstr *name_info, struct fscrypt_name *fname); /* * node.c */ struct dnode_of_data; struct node_info; int f2fs_check_nid_range(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_available_free_memory(struct f2fs_sb_info *sbi, int type); bool f2fs_in_warm_node_list(struct f2fs_sb_info *sbi, struct page *page); void f2fs_init_fsync_node_info(struct f2fs_sb_info *sbi); void f2fs_del_fsync_node_entry(struct f2fs_sb_info *sbi, struct page *page); void f2fs_reset_fsync_node_info(struct f2fs_sb_info *sbi); int f2fs_need_dentry_mark(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_is_checkpointed_node(struct f2fs_sb_info *sbi, nid_t nid); bool f2fs_need_inode_block_update(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_get_node_info(struct f2fs_sb_info *sbi, nid_t nid, struct node_info *ni); pgoff_t f2fs_get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs); int f2fs_get_dnode_of_data(struct dnode_of_data *dn, pgoff_t index, int mode); int f2fs_truncate_inode_blocks(struct inode *inode, pgoff_t from); int f2fs_truncate_xattr_node(struct inode *inode); int f2fs_wait_on_node_pages_writeback(struct f2fs_sb_info *sbi, unsigned int seq_id); int f2fs_remove_inode_page(struct inode *inode); struct page *f2fs_new_inode_page(struct inode *inode); struct page *f2fs_new_node_page(struct dnode_of_data *dn, unsigned int ofs); void f2fs_ra_node_page(struct f2fs_sb_info *sbi, nid_t nid); struct page *f2fs_get_node_page(struct f2fs_sb_info *sbi, pgoff_t nid); struct page *f2fs_get_node_page_ra(struct page *parent, int start); int f2fs_move_node_page(struct page *node_page, int gc_type); int f2fs_fsync_node_pages(struct f2fs_sb_info *sbi, struct inode *inode, struct writeback_control *wbc, bool atomic, unsigned int *seq_id); int f2fs_sync_node_pages(struct f2fs_sb_info *sbi, struct writeback_control *wbc, bool do_balance, enum iostat_type io_type); int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount); bool f2fs_alloc_nid(struct f2fs_sb_info *sbi, nid_t *nid); void f2fs_alloc_nid_done(struct f2fs_sb_info *sbi, nid_t nid); void f2fs_alloc_nid_failed(struct f2fs_sb_info *sbi, nid_t nid); int f2fs_try_to_free_nids(struct f2fs_sb_info *sbi, int nr_shrink); void f2fs_recover_inline_xattr(struct inode *inode, struct page *page); int f2fs_recover_xattr_data(struct inode *inode, struct page *page); int f2fs_recover_inode_page(struct f2fs_sb_info *sbi, struct page *page); int f2fs_restore_node_summary(struct f2fs_sb_info *sbi, unsigned int segno, struct f2fs_summary_block *sum); int f2fs_flush_nat_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_node_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_node_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_node_manager_caches(void); void f2fs_destroy_node_manager_caches(void); /* * segment.c */ bool f2fs_need_SSR(struct f2fs_sb_info *sbi); void f2fs_register_inmem_page(struct inode *inode, struct page *page); void f2fs_drop_inmem_pages_all(struct f2fs_sb_info *sbi, bool gc_failure); void f2fs_drop_inmem_pages(struct inode *inode); void f2fs_drop_inmem_page(struct inode *inode, struct page *page); int f2fs_commit_inmem_pages(struct inode *inode); void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need); void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi); int f2fs_issue_flush(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_create_flush_cmd_control(struct f2fs_sb_info *sbi); int f2fs_flush_device_cache(struct f2fs_sb_info *sbi); void f2fs_destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free); void f2fs_invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr); bool f2fs_is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_drop_discard_cmd(struct f2fs_sb_info *sbi); void f2fs_stop_discard_thread(struct f2fs_sb_info *sbi); bool f2fs_issue_discard_timeout(struct f2fs_sb_info *sbi); void f2fs_clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_dirty_to_prefree(struct f2fs_sb_info *sbi); block_t f2fs_get_unusable_blocks(struct f2fs_sb_info *sbi); int f2fs_disable_cp_again(struct f2fs_sb_info *sbi, block_t unusable); void f2fs_release_discard_addrs(struct f2fs_sb_info *sbi); int f2fs_npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra); void allocate_segment_for_resize(struct f2fs_sb_info *sbi, int type, unsigned int start, unsigned int end); void f2fs_allocate_new_segments(struct f2fs_sb_info *sbi); int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range); bool f2fs_exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc); struct page *f2fs_get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno); void f2fs_update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr); void f2fs_do_write_meta_page(struct f2fs_sb_info *sbi, struct page *page, enum iostat_type io_type); void f2fs_do_write_node_page(unsigned int nid, struct f2fs_io_info *fio); void f2fs_outplace_write_data(struct dnode_of_data *dn, struct f2fs_io_info *fio); int f2fs_inplace_write_data(struct f2fs_io_info *fio); void f2fs_do_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum, block_t old_blkaddr, block_t new_blkaddr, bool recover_curseg, bool recover_newaddr); void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn, block_t old_addr, block_t new_addr, unsigned char version, bool recover_curseg, bool recover_newaddr); void f2fs_allocate_data_block(struct f2fs_sb_info *sbi, struct page *page, block_t old_blkaddr, block_t *new_blkaddr, struct f2fs_summary *sum, int type, struct f2fs_io_info *fio, bool add_list); void f2fs_wait_on_page_writeback(struct page *page, enum page_type type, bool ordered, bool locked); void f2fs_wait_on_block_writeback(struct inode *inode, block_t blkaddr); void f2fs_wait_on_block_writeback_range(struct inode *inode, block_t blkaddr, block_t len); void f2fs_write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk); void f2fs_write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk); int f2fs_lookup_journal_in_cursum(struct f2fs_journal *journal, int type, unsigned int val, int alloc); void f2fs_flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc); int f2fs_build_segment_manager(struct f2fs_sb_info *sbi); void f2fs_destroy_segment_manager(struct f2fs_sb_info *sbi); int __init f2fs_create_segment_manager_caches(void); void f2fs_destroy_segment_manager_caches(void); int f2fs_rw_hint_to_seg_type(enum rw_hint hint); enum rw_hint f2fs_io_type_to_rw_hint(struct f2fs_sb_info *sbi, enum page_type type, enum temp_type temp); /* * checkpoint.c */ void f2fs_stop_checkpoint(struct f2fs_sb_info *sbi, bool end_io); struct page *f2fs_grab_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_meta_page_nofail(struct f2fs_sb_info *sbi, pgoff_t index); struct page *f2fs_get_tmp_page(struct f2fs_sb_info *sbi, pgoff_t index); bool f2fs_is_valid_blkaddr(struct f2fs_sb_info *sbi, block_t blkaddr, int type); int f2fs_ra_meta_pages(struct f2fs_sb_info *sbi, block_t start, int nrpages, int type, bool sync); void f2fs_ra_meta_pages_cond(struct f2fs_sb_info *sbi, pgoff_t index); long f2fs_sync_meta_pages(struct f2fs_sb_info *sbi, enum page_type type, long nr_to_write, enum iostat_type io_type); void f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_remove_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, int type); void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all); bool f2fs_exist_written_data(struct f2fs_sb_info *sbi, nid_t ino, int mode); void f2fs_set_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); bool f2fs_is_dirty_device(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type); int f2fs_sync_inode_meta(struct f2fs_sb_info *sbi); int f2fs_acquire_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_release_orphan_inode(struct f2fs_sb_info *sbi); void f2fs_add_orphan_inode(struct inode *inode); void f2fs_remove_orphan_inode(struct f2fs_sb_info *sbi, nid_t ino); int f2fs_recover_orphan_inodes(struct f2fs_sb_info *sbi); int f2fs_get_valid_checkpoint(struct f2fs_sb_info *sbi); void f2fs_update_dirty_page(struct inode *inode, struct page *page); void f2fs_remove_dirty_inode(struct inode *inode); int f2fs_sync_dirty_inodes(struct f2fs_sb_info *sbi, enum inode_type type); void f2fs_wait_on_all_pages_writeback(struct f2fs_sb_info *sbi); int f2fs_write_checkpoint(struct f2fs_sb_info *sbi, struct cp_control *cpc); void f2fs_init_ino_entry_info(struct f2fs_sb_info *sbi); int __init f2fs_create_checkpoint_caches(void); void f2fs_destroy_checkpoint_caches(void); /* * data.c */ int f2fs_init_post_read_processing(void); void f2fs_destroy_post_read_processing(void); void f2fs_submit_merged_write(struct f2fs_sb_info *sbi, enum page_type type); void f2fs_submit_merged_write_cond(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, nid_t ino, enum page_type type); void f2fs_flush_merged_writes(struct f2fs_sb_info *sbi); int f2fs_submit_page_bio(struct f2fs_io_info *fio); int f2fs_merge_page_bio(struct f2fs_io_info *fio); void f2fs_submit_page_write(struct f2fs_io_info *fio); struct block_device *f2fs_target_device(struct f2fs_sb_info *sbi, block_t blk_addr, struct bio *bio); int f2fs_target_device_index(struct f2fs_sb_info *sbi, block_t blkaddr); void f2fs_set_data_blkaddr(struct dnode_of_data *dn); void f2fs_update_data_blkaddr(struct dnode_of_data *dn, block_t blkaddr); int f2fs_reserve_new_blocks(struct dnode_of_data *dn, blkcnt_t count); int f2fs_reserve_new_block(struct dnode_of_data *dn); int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index); int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *from); int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index); struct page *f2fs_get_read_data_page(struct inode *inode, pgoff_t index, int op_flags, bool for_write); struct page *f2fs_find_data_page(struct inode *inode, pgoff_t index); struct page *f2fs_get_lock_data_page(struct inode *inode, pgoff_t index, bool for_write); struct page *f2fs_get_new_data_page(struct inode *inode, struct page *ipage, pgoff_t index, bool new_i_size); int f2fs_do_write_data_page(struct f2fs_io_info *fio); void __do_map_lock(struct f2fs_sb_info *sbi, int flag, bool lock); int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int create, int flag); int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len); bool f2fs_should_update_inplace(struct inode *inode, struct f2fs_io_info *fio); bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio); void f2fs_invalidate_page(struct page *page, unsigned int offset, unsigned int length); int f2fs_release_page(struct page *page, gfp_t wait); #ifdef CONFIG_MIGRATION int f2fs_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode); #endif bool f2fs_overwrite_io(struct inode *inode, loff_t pos, size_t len); void f2fs_clear_page_cache_dirty_tag(struct page *page); /* * gc.c */ int f2fs_start_gc_thread(struct f2fs_sb_info *sbi); void f2fs_stop_gc_thread(struct f2fs_sb_info *sbi); block_t f2fs_start_bidx_of_node(unsigned int node_ofs, struct inode *inode); int f2fs_gc(struct f2fs_sb_info *sbi, bool sync, bool background, unsigned int segno); void f2fs_build_gc_manager(struct f2fs_sb_info *sbi); int f2fs_resize_fs(struct f2fs_sb_info *sbi, __u64 block_count); /* * recovery.c */ int f2fs_recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only); bool f2fs_space_for_roll_forward(struct f2fs_sb_info *sbi); /* * debug.c */ #ifdef CONFIG_F2FS_STAT_FS struct f2fs_stat_info { struct list_head stat_list; struct f2fs_sb_info *sbi; int all_area_segs, sit_area_segs, nat_area_segs, ssa_area_segs; int main_area_segs, main_area_sections, main_area_zones; unsigned long long hit_largest, hit_cached, hit_rbtree; unsigned long long hit_total, total_ext; int ext_tree, zombie_tree, ext_node; int ndirty_node, ndirty_dent, ndirty_meta, ndirty_imeta; int ndirty_data, ndirty_qdata; int inmem_pages; unsigned int ndirty_dirs, ndirty_files, nquota_files, ndirty_all; int nats, dirty_nats, sits, dirty_sits; int free_nids, avail_nids, alloc_nids; int total_count, utilization; int bg_gc, nr_wb_cp_data, nr_wb_data; int nr_rd_data, nr_rd_node, nr_rd_meta; int nr_dio_read, nr_dio_write; unsigned int io_skip_bggc, other_skip_bggc; int nr_flushing, nr_flushed, flush_list_empty; int nr_discarding, nr_discarded; int nr_discard_cmd; unsigned int undiscard_blks; int inline_xattr, inline_inode, inline_dir, append, update, orphans; int aw_cnt, max_aw_cnt, vw_cnt, max_vw_cnt; unsigned int valid_count, valid_node_count, valid_inode_count, discard_blks; unsigned int bimodal, avg_vblocks; int util_free, util_valid, util_invalid; int rsvd_segs, overp_segs; int dirty_count, node_pages, meta_pages; int prefree_count, call_count, cp_count, bg_cp_count; int tot_segs, node_segs, data_segs, free_segs, free_secs; int bg_node_segs, bg_data_segs; int tot_blks, data_blks, node_blks; int bg_data_blks, bg_node_blks; unsigned long long skipped_atomic_files[2]; int curseg[NR_CURSEG_TYPE]; int cursec[NR_CURSEG_TYPE]; int curzone[NR_CURSEG_TYPE]; unsigned int meta_count[META_MAX]; unsigned int segment_count[2]; unsigned int block_count[2]; unsigned int inplace_count; unsigned long long base_mem, cache_mem, page_mem; }; static inline struct f2fs_stat_info *F2FS_STAT(struct f2fs_sb_info *sbi) { return (struct f2fs_stat_info *)sbi->stat_info; } #define stat_inc_cp_count(si) ((si)->cp_count++) #define stat_inc_bg_cp_count(si) ((si)->bg_cp_count++) #define stat_inc_call_count(si) ((si)->call_count++) #define stat_inc_bggc_count(sbi) ((sbi)->bg_gc++) #define stat_io_skip_bggc_count(sbi) ((sbi)->io_skip_bggc++) #define stat_other_skip_bggc_count(sbi) ((sbi)->other_skip_bggc++) #define stat_inc_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]++) #define stat_dec_dirty_inode(sbi, type) ((sbi)->ndirty_inode[type]--) #define stat_inc_total_hit(sbi) (atomic64_inc(&(sbi)->total_hit_ext)) #define stat_inc_rbtree_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_rbtree)) #define stat_inc_largest_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_largest)) #define stat_inc_cached_node_hit(sbi) (atomic64_inc(&(sbi)->read_hit_cached)) #define stat_inc_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_dec_inline_xattr(inode) \ do { \ if (f2fs_has_inline_xattr(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_xattr)); \ } while (0) #define stat_inc_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_dec_inline_inode(inode) \ do { \ if (f2fs_has_inline_data(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_inode)); \ } while (0) #define stat_inc_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_inc(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_dec_inline_dir(inode) \ do { \ if (f2fs_has_inline_dentry(inode)) \ (atomic_dec(&F2FS_I_SB(inode)->inline_dir)); \ } while (0) #define stat_inc_meta_count(sbi, blkaddr) \ do { \ if (blkaddr < SIT_I(sbi)->sit_base_addr) \ atomic_inc(&(sbi)->meta_count[META_CP]); \ else if (blkaddr < NM_I(sbi)->nat_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SIT]); \ else if (blkaddr < SM_I(sbi)->ssa_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_NAT]); \ else if (blkaddr < SM_I(sbi)->main_blkaddr) \ atomic_inc(&(sbi)->meta_count[META_SSA]); \ } while (0) #define stat_inc_seg_type(sbi, curseg) \ ((sbi)->segment_count[(curseg)->alloc_type]++) #define stat_inc_block_count(sbi, curseg) \ ((sbi)->block_count[(curseg)->alloc_type]++) #define stat_inc_inplace_blocks(sbi) \ (atomic_inc(&(sbi)->inplace_count)) #define stat_inc_atomic_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->aw_cnt)) #define stat_dec_atomic_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->aw_cnt)) #define stat_update_max_atomic_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->aw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_aw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_aw_cnt, cur); \ } while (0) #define stat_inc_volatile_write(inode) \ (atomic_inc(&F2FS_I_SB(inode)->vw_cnt)) #define stat_dec_volatile_write(inode) \ (atomic_dec(&F2FS_I_SB(inode)->vw_cnt)) #define stat_update_max_volatile_write(inode) \ do { \ int cur = atomic_read(&F2FS_I_SB(inode)->vw_cnt); \ int max = atomic_read(&F2FS_I_SB(inode)->max_vw_cnt); \ if (cur > max) \ atomic_set(&F2FS_I_SB(inode)->max_vw_cnt, cur); \ } while (0) #define stat_inc_seg_count(sbi, type, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ si->tot_segs++; \ if ((type) == SUM_TYPE_DATA) { \ si->data_segs++; \ si->bg_data_segs += (gc_type == BG_GC) ? 1 : 0; \ } else { \ si->node_segs++; \ si->bg_node_segs += (gc_type == BG_GC) ? 1 : 0; \ } \ } while (0) #define stat_inc_tot_blk_count(si, blks) \ ((si)->tot_blks += (blks)) #define stat_inc_data_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->data_blks += (blks); \ si->bg_data_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) \ do { \ struct f2fs_stat_info *si = F2FS_STAT(sbi); \ stat_inc_tot_blk_count(si, blks); \ si->node_blks += (blks); \ si->bg_node_blks += ((gc_type) == BG_GC) ? (blks) : 0; \ } while (0) int f2fs_build_stats(struct f2fs_sb_info *sbi); void f2fs_destroy_stats(struct f2fs_sb_info *sbi); void __init f2fs_create_root_stats(void); void f2fs_destroy_root_stats(void); #else #define stat_inc_cp_count(si) do { } while (0) #define stat_inc_bg_cp_count(si) do { } while (0) #define stat_inc_call_count(si) do { } while (0) #define stat_inc_bggc_count(si) do { } while (0) #define stat_io_skip_bggc_count(sbi) do { } while (0) #define stat_other_skip_bggc_count(sbi) do { } while (0) #define stat_inc_dirty_inode(sbi, type) do { } while (0) #define stat_dec_dirty_inode(sbi, type) do { } while (0) #define stat_inc_total_hit(sb) do { } while (0) #define stat_inc_rbtree_node_hit(sb) do { } while (0) #define stat_inc_largest_node_hit(sbi) do { } while (0) #define stat_inc_cached_node_hit(sbi) do { } while (0) #define stat_inc_inline_xattr(inode) do { } while (0) #define stat_dec_inline_xattr(inode) do { } while (0) #define stat_inc_inline_inode(inode) do { } while (0) #define stat_dec_inline_inode(inode) do { } while (0) #define stat_inc_inline_dir(inode) do { } while (0) #define stat_dec_inline_dir(inode) do { } while (0) #define stat_inc_atomic_write(inode) do { } while (0) #define stat_dec_atomic_write(inode) do { } while (0) #define stat_update_max_atomic_write(inode) do { } while (0) #define stat_inc_volatile_write(inode) do { } while (0) #define stat_dec_volatile_write(inode) do { } while (0) #define stat_update_max_volatile_write(inode) do { } while (0) #define stat_inc_meta_count(sbi, blkaddr) do { } while (0) #define stat_inc_seg_type(sbi, curseg) do { } while (0) #define stat_inc_block_count(sbi, curseg) do { } while (0) #define stat_inc_inplace_blocks(sbi) do { } while (0) #define stat_inc_seg_count(sbi, type, gc_type) do { } while (0) #define stat_inc_tot_blk_count(si, blks) do { } while (0) #define stat_inc_data_blk_count(sbi, blks, gc_type) do { } while (0) #define stat_inc_node_blk_count(sbi, blks, gc_type) do { } while (0) static inline int f2fs_build_stats(struct f2fs_sb_info *sbi) { return 0; } static inline void f2fs_destroy_stats(struct f2fs_sb_info *sbi) { } static inline void __init f2fs_create_root_stats(void) { } static inline void f2fs_destroy_root_stats(void) { } #endif extern const struct file_operations f2fs_dir_operations; extern const struct file_operations f2fs_file_operations; extern const struct inode_operations f2fs_file_inode_operations; extern const struct address_space_operations f2fs_dblock_aops; extern const struct address_space_operations f2fs_node_aops; extern const struct address_space_operations f2fs_meta_aops; extern const struct inode_operations f2fs_dir_inode_operations; extern const struct inode_operations f2fs_symlink_inode_operations; extern const struct inode_operations f2fs_encrypted_symlink_inode_operations; extern const struct inode_operations f2fs_special_inode_operations; extern struct kmem_cache *f2fs_inode_entry_slab; /* * inline.c */ bool f2fs_may_inline_data(struct inode *inode); bool f2fs_may_inline_dentry(struct inode *inode); void f2fs_do_read_inline_data(struct page *page, struct page *ipage); void f2fs_truncate_inline_inode(struct inode *inode, struct page *ipage, u64 from); int f2fs_read_inline_data(struct inode *inode, struct page *page); int f2fs_convert_inline_page(struct dnode_of_data *dn, struct page *page); int f2fs_convert_inline_inode(struct inode *inode); int f2fs_write_inline_data(struct inode *inode, struct page *page); bool f2fs_recover_inline_data(struct inode *inode, struct page *npage); struct f2fs_dir_entry *f2fs_find_in_inline_dir(struct inode *dir, struct fscrypt_name *fname, struct page **res_page); int f2fs_make_empty_inline_dir(struct inode *inode, struct inode *parent, struct page *ipage); int f2fs_add_inline_entry(struct inode *dir, const struct qstr *new_name, const struct qstr *orig_name, struct inode *inode, nid_t ino, umode_t mode); void f2fs_delete_inline_entry(struct f2fs_dir_entry *dentry, struct page *page, struct inode *dir, struct inode *inode); bool f2fs_empty_inline_dir(struct inode *dir); int f2fs_read_inline_dir(struct file *file, struct dir_context *ctx, struct fscrypt_str *fstr); int f2fs_inline_data_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len); /* * shrinker.c */ unsigned long f2fs_shrink_count(struct shrinker *shrink, struct shrink_control *sc); unsigned long f2fs_shrink_scan(struct shrinker *shrink, struct shrink_control *sc); void f2fs_join_shrinker(struct f2fs_sb_info *sbi); void f2fs_leave_shrinker(struct f2fs_sb_info *sbi); /* * extent_cache.c */ struct rb_entry *f2fs_lookup_rb_tree(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs); struct rb_node **f2fs_lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi, struct rb_root_cached *root, struct rb_node **parent, unsigned int ofs, bool *leftmost); struct rb_entry *f2fs_lookup_rb_tree_ret(struct rb_root_cached *root, struct rb_entry *cached_re, unsigned int ofs, struct rb_entry **prev_entry, struct rb_entry **next_entry, struct rb_node ***insert_p, struct rb_node **insert_parent, bool force, bool *leftmost); bool f2fs_check_rb_tree_consistence(struct f2fs_sb_info *sbi, struct rb_root_cached *root); unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink); bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext); void f2fs_drop_extent_tree(struct inode *inode); unsigned int f2fs_destroy_extent_node(struct inode *inode); void f2fs_destroy_extent_tree(struct inode *inode); bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs, struct extent_info *ei); void f2fs_update_extent_cache(struct dnode_of_data *dn); void f2fs_update_extent_cache_range(struct dnode_of_data *dn, pgoff_t fofs, block_t blkaddr, unsigned int len); void f2fs_init_extent_cache_info(struct f2fs_sb_info *sbi); int __init f2fs_create_extent_cache(void); void f2fs_destroy_extent_cache(void); /* * sysfs.c */ int __init f2fs_init_sysfs(void); void f2fs_exit_sysfs(void); int f2fs_register_sysfs(struct f2fs_sb_info *sbi); void f2fs_unregister_sysfs(struct f2fs_sb_info *sbi); /* * crypto support */ static inline bool f2fs_encrypted_file(struct inode *inode) { return IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode); } static inline void f2fs_set_encrypted_inode(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION file_set_encrypt(inode); f2fs_set_inode_flags(inode); #endif } /* * Returns true if the reads of the inode's data need to undergo some * postprocessing step, like decryption or authenticity verification. */ static inline bool f2fs_post_read_required(struct inode *inode) { return f2fs_encrypted_file(inode); } #define F2FS_FEATURE_FUNCS(name, flagname) \ static inline int f2fs_sb_has_##name(struct f2fs_sb_info *sbi) \ { \ return F2FS_HAS_FEATURE(sbi, F2FS_FEATURE_##flagname); \ } F2FS_FEATURE_FUNCS(encrypt, ENCRYPT); F2FS_FEATURE_FUNCS(blkzoned, BLKZONED); F2FS_FEATURE_FUNCS(extra_attr, EXTRA_ATTR); F2FS_FEATURE_FUNCS(project_quota, PRJQUOTA); F2FS_FEATURE_FUNCS(inode_chksum, INODE_CHKSUM); F2FS_FEATURE_FUNCS(flexible_inline_xattr, FLEXIBLE_INLINE_XATTR); F2FS_FEATURE_FUNCS(quota_ino, QUOTA_INO); F2FS_FEATURE_FUNCS(inode_crtime, INODE_CRTIME); F2FS_FEATURE_FUNCS(lost_found, LOST_FOUND); F2FS_FEATURE_FUNCS(sb_chksum, SB_CHKSUM); #ifdef CONFIG_BLK_DEV_ZONED static inline bool f2fs_blkz_is_seq(struct f2fs_sb_info *sbi, int devi, block_t blkaddr) { unsigned int zno = blkaddr >> sbi->log_blocks_per_blkz; return test_bit(zno, FDEV(devi).blkz_seq); } #endif static inline bool f2fs_hw_should_discard(struct f2fs_sb_info *sbi) { return f2fs_sb_has_blkzoned(sbi); } static inline bool f2fs_bdev_support_discard(struct block_device *bdev) { return blk_queue_discard(bdev_get_queue(bdev)) || bdev_is_zoned(bdev); } static inline bool f2fs_hw_support_discard(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return f2fs_bdev_support_discard(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (f2fs_bdev_support_discard(FDEV(i).bdev)) return true; return false; } static inline bool f2fs_realtime_discard_enable(struct f2fs_sb_info *sbi) { return (test_opt(sbi, DISCARD) && f2fs_hw_support_discard(sbi)) || f2fs_hw_should_discard(sbi); } static inline bool f2fs_hw_is_readonly(struct f2fs_sb_info *sbi) { int i; if (!f2fs_is_multi_device(sbi)) return bdev_read_only(sbi->sb->s_bdev); for (i = 0; i < sbi->s_ndevs; i++) if (bdev_read_only(FDEV(i).bdev)) return true; return false; } static inline void set_opt_mode(struct f2fs_sb_info *sbi, unsigned int mt) { clear_opt(sbi, ADAPTIVE); clear_opt(sbi, LFS); switch (mt) { case F2FS_MOUNT_ADAPTIVE: set_opt(sbi, ADAPTIVE); break; case F2FS_MOUNT_LFS: set_opt(sbi, LFS); break; } } static inline bool f2fs_may_encrypt(struct inode *inode) { #ifdef CONFIG_FS_ENCRYPTION umode_t mode = inode->i_mode; return (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)); #else return false; #endif } static inline int block_unaligned_IO(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { unsigned int i_blkbits = READ_ONCE(inode->i_blkbits); unsigned int blocksize_mask = (1 << i_blkbits) - 1; loff_t offset = iocb->ki_pos; unsigned long align = offset | iov_iter_alignment(iter); return align & blocksize_mask; } static inline int allow_outplace_dio(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); return (test_opt(sbi, LFS) && (rw == WRITE) && !block_unaligned_IO(inode, iocb, iter)); } static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED) && !(inode->i_flags & S_SWAPFILE)) return true; return false; } #ifdef CONFIG_F2FS_FAULT_INJECTION extern void f2fs_build_fault_attr(struct f2fs_sb_info *sbi, unsigned int rate, unsigned int type); #else #define f2fs_build_fault_attr(sbi, rate, type) do { } while (0) #endif static inline bool is_journalled_quota(struct f2fs_sb_info *sbi) { #ifdef CONFIG_QUOTA if (f2fs_sb_has_quota_ino(sbi)) return true; if (F2FS_OPTION(sbi).s_qf_names[USRQUOTA] || F2FS_OPTION(sbi).s_qf_names[GRPQUOTA] || F2FS_OPTION(sbi).s_qf_names[PRJQUOTA]) return true; #endif return false; } #define EFSBADCRC EBADMSG /* Bad CRC detected */ #define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */ #endif /* _LINUX_F2FS_H */
} static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED)) return true;
} static inline bool f2fs_force_buffered_io(struct inode *inode, struct kiocb *iocb, struct iov_iter *iter) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); int rw = iov_iter_rw(iter); if (f2fs_post_read_required(inode)) return true; if (f2fs_is_multi_device(sbi)) return true; /* * for blkzoned device, fallback direct IO to buffered IO, so * all IOs can be serialized by log-structured write. */ if (f2fs_sb_has_blkzoned(sbi)) return true; if (test_opt(sbi, LFS) && (rw == WRITE) && block_unaligned_IO(inode, iocb, iter)) return true; if (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED) && !(inode->i_flags & S_SWAPFILE)) return true;
{'added': [(1501, '\treturn F2FS_M_SB(page_file_mapping(page));'), (3686, '\tif (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED) &&'), (3687, '\t\t\t\t\t!(inode->i_flags & S_SWAPFILE))')], 'deleted': [(1501, '\treturn F2FS_M_SB(page->mapping);'), (3686, '\tif (is_sbi_flag_set(F2FS_I_SB(inode), SBI_CP_DISABLED))')]}
3
2
2,531
14,991
https://github.com/torvalds/linux
CVE-2019-19815
['CWE-476']
parsetok.c
parsetok
/* Parser-tokenizer link implementation */ #include "pgenheaders.h" #include "tokenizer.h" #include "node.h" #include "grammar.h" #include "parser.h" #include "parsetok.h" #include "errcode.h" #include "graminit.h" /* Forward */ static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int *); static int initerr(perrdetail *err_ret, PyObject * filename); /* Parse input coming from a string. Return error code, print some errors. */ node * Ta3Parser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { return Ta3Parser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * Ta3Parser_ParseStringFlags(const char *s, grammar *g, int start, perrdetail *err_ret, int flags) { return Ta3Parser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, flags); } node * Ta3Parser_ParseStringFlagsFilename(const char *s, const char *filename, grammar *g, int start, perrdetail *err_ret, int flags) { int iflags = flags; return Ta3Parser_ParseStringFlagsFilenameEx(s, filename, g, start, err_ret, &iflags); } node * Ta3Parser_ParseStringObject(const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags) { struct tok_state *tok; int exec_input = start == file_input; if (initerr(err_ret, filename) < 0) return NULL; if (*flags & PyPARSE_IGNORE_COOKIE) tok = Ta3Tokenizer_FromUTF8(s, exec_input); else tok = Ta3Tokenizer_FromString(s, exec_input); if (tok == NULL) { err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } node * Ta3Parser_ParseStringFlagsFilenameEx(const char *s, const char *filename_str, grammar *g, int start, perrdetail *err_ret, int *flags) { node *n; PyObject *filename = NULL; #ifndef PGEN if (filename_str != NULL) { filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = Ta3Parser_ParseStringObject(s, filename, g, start, err_ret, flags); #ifndef PGEN Py_XDECREF(filename); #endif return n; } /* Parse input coming from a file. Return error code, print some errors. */ node * Ta3Parser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret) { return Ta3Parser_ParseFileFlags(fp, filename, NULL, g, start, ps1, ps2, err_ret, 0); } node * Ta3Parser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int flags) { int iflags = flags; return Ta3Parser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, ps2, err_ret, &iflags); } node * Ta3Parser_ParseFileObject(FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { struct tok_state *tok; if (initerr(err_ret, filename) < 0) return NULL; if ((tok = Ta3Tokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } node * Ta3Parser_ParseFileFlagsEx(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { node *n; PyObject *fileobj = NULL; #ifndef PGEN if (filename != NULL) { fileobj = PyUnicode_DecodeFSDefault(filename); if (fileobj == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = Ta3Parser_ParseFileObject(fp, fileobj, enc, g, start, ps1, ps2, err_ret, flags); #ifndef PGEN Py_XDECREF(fileobj); #endif return n; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 static const char with_msg[] = "%s:%d: Warning: 'with' will become a reserved keyword in Python 2.6\n"; static const char as_msg[] = "%s:%d: Warning: 'as' will become a reserved keyword in Python 2.6\n"; static void warn(const char *msg, const char *filename, int lineno) { if (filename == NULL) filename = "<string>"; PySys_WriteStderr(msg, filename, lineno); } #endif #endif typedef struct { int *items; size_t size; size_t num_items; } growable_int_array; int growable_int_array_init(growable_int_array *arr, size_t initial_size) { assert(initial_size > 0); arr->items = malloc(initial_size * sizeof(*arr->items)); arr->size = initial_size; arr->num_items = 0; return arr->items != NULL; } int growable_int_array_add(growable_int_array *arr, int item) { if (arr->num_items >= arr->size) { arr->size *= 2; arr->items = realloc(arr->items, arr->size * sizeof(*arr->items)); if (!arr->items) return 0; } arr->items[arr->num_items] = item; arr->num_items++; return 1; } void growable_int_array_deallocate(growable_int_array *arr) { free(arr->items); } /* Parse input coming from the given tokenizer structure. Return error code. */ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; growable_int_array type_ignores; if (!growable_int_array_init(&type_ignores, 10)) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } if ((ps = Ta3Parser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; int col_offset; type = Ta3Tokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = b - a; /* XXX this may compute NULL - NULL */ str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->text = "with Barry as BDFL, use '<>' " "instead of '!='"; err_ret->error = E_SYNTAX; break; } } #endif if (a >= tok->line_start) col_offset = Py_SAFE_DOWNCAST(a - tok->line_start, intptr_t, int); else col_offset = -1; if (type == TYPE_IGNORE) { if (!growable_int_array_add(&type_ignores, tok->lineno)) { err_ret->error = E_NOMEM; break; } continue; } if ((err_ret->error = Ta3Parser_AddToken(ps, (int)type, str, tok->lineno, col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; if (n->n_type == file_input) { /* Put type_ignore nodes in the ENDMARKER of file_input. */ int num; node *ch; size_t i; num = NCH(n); ch = CHILD(n, num - 1); REQ(ch, ENDMARKER); for (i = 0; i < type_ignores.num_items; i++) { Ta3Node_AddChild(ch, TYPE_IGNORE, NULL, type_ignores.items[i], 0); } } growable_int_array_deallocate(&type_ignores); #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; Ta3Node_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif Ta3Parser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = Ta3Node_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: Ta3Tokenizer_Free(tok); return n; } static int initerr(perrdetail *err_ret, PyObject *filename) { err_ret->error = E_OK; err_ret->lineno = 0; err_ret->offset = 0; err_ret->text = NULL; err_ret->token = -1; err_ret->expected = -1; #ifndef PGEN if (filename) { Py_INCREF(filename); err_ret->filename = filename; } else { err_ret->filename = PyUnicode_FromString("<string>"); if (err_ret->filename == NULL) { err_ret->error = E_ERROR; return -1; } } #endif return 0; }
/* Parser-tokenizer link implementation */ #include "pgenheaders.h" #include "tokenizer.h" #include "node.h" #include "grammar.h" #include "parser.h" #include "parsetok.h" #include "errcode.h" #include "graminit.h" /* Forward */ static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int *); static int initerr(perrdetail *err_ret, PyObject * filename); /* Parse input coming from a string. Return error code, print some errors. */ node * Ta3Parser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { return Ta3Parser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * Ta3Parser_ParseStringFlags(const char *s, grammar *g, int start, perrdetail *err_ret, int flags) { return Ta3Parser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, flags); } node * Ta3Parser_ParseStringFlagsFilename(const char *s, const char *filename, grammar *g, int start, perrdetail *err_ret, int flags) { int iflags = flags; return Ta3Parser_ParseStringFlagsFilenameEx(s, filename, g, start, err_ret, &iflags); } node * Ta3Parser_ParseStringObject(const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags) { struct tok_state *tok; int exec_input = start == file_input; if (initerr(err_ret, filename) < 0) return NULL; if (*flags & PyPARSE_IGNORE_COOKIE) tok = Ta3Tokenizer_FromUTF8(s, exec_input); else tok = Ta3Tokenizer_FromString(s, exec_input); if (tok == NULL) { err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif if (*flags & PyPARSE_ASYNC_ALWAYS) tok->async_always = 1; return parsetok(tok, g, start, err_ret, flags); } node * Ta3Parser_ParseStringFlagsFilenameEx(const char *s, const char *filename_str, grammar *g, int start, perrdetail *err_ret, int *flags) { node *n; PyObject *filename = NULL; #ifndef PGEN if (filename_str != NULL) { filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = Ta3Parser_ParseStringObject(s, filename, g, start, err_ret, flags); #ifndef PGEN Py_XDECREF(filename); #endif return n; } /* Parse input coming from a file. Return error code, print some errors. */ node * Ta3Parser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret) { return Ta3Parser_ParseFileFlags(fp, filename, NULL, g, start, ps1, ps2, err_ret, 0); } node * Ta3Parser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int flags) { int iflags = flags; return Ta3Parser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, ps2, err_ret, &iflags); } node * Ta3Parser_ParseFileObject(FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { struct tok_state *tok; if (initerr(err_ret, filename) < 0) return NULL; if ((tok = Ta3Tokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } node * Ta3Parser_ParseFileFlagsEx(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { node *n; PyObject *fileobj = NULL; #ifndef PGEN if (filename != NULL) { fileobj = PyUnicode_DecodeFSDefault(filename); if (fileobj == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = Ta3Parser_ParseFileObject(fp, fileobj, enc, g, start, ps1, ps2, err_ret, flags); #ifndef PGEN Py_XDECREF(fileobj); #endif return n; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 static const char with_msg[] = "%s:%d: Warning: 'with' will become a reserved keyword in Python 2.6\n"; static const char as_msg[] = "%s:%d: Warning: 'as' will become a reserved keyword in Python 2.6\n"; static void warn(const char *msg, const char *filename, int lineno) { if (filename == NULL) filename = "<string>"; PySys_WriteStderr(msg, filename, lineno); } #endif #endif typedef struct { int *items; size_t size; size_t num_items; } growable_int_array; int growable_int_array_init(growable_int_array *arr, size_t initial_size) { assert(initial_size > 0); arr->items = malloc(initial_size * sizeof(*arr->items)); arr->size = initial_size; arr->num_items = 0; return arr->items != NULL; } int growable_int_array_add(growable_int_array *arr, int item) { if (arr->num_items >= arr->size) { arr->size *= 2; arr->items = realloc(arr->items, arr->size * sizeof(*arr->items)); if (!arr->items) return 0; } arr->items[arr->num_items] = item; arr->num_items++; return 1; } void growable_int_array_deallocate(growable_int_array *arr) { free(arr->items); } /* Parse input coming from the given tokenizer structure. Return error code. */ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; growable_int_array type_ignores; if (!growable_int_array_init(&type_ignores, 10)) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } if ((ps = Ta3Parser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; int col_offset; type = Ta3Tokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = (a != NULL && b != NULL) ? b - a : 0; str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->expected = NOTEQUAL; err_ret->error = E_SYNTAX; break; } } #endif if (a != NULL && a >= tok->line_start) { col_offset = Py_SAFE_DOWNCAST(a - tok->line_start, intptr_t, int); } else { col_offset = -1; } if (type == TYPE_IGNORE) { if (!growable_int_array_add(&type_ignores, tok->lineno)) { err_ret->error = E_NOMEM; break; } continue; } if ((err_ret->error = Ta3Parser_AddToken(ps, (int)type, str, tok->lineno, col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; if (n->n_type == file_input) { /* Put type_ignore nodes in the ENDMARKER of file_input. */ int num; node *ch; size_t i; num = NCH(n); ch = CHILD(n, num - 1); REQ(ch, ENDMARKER); for (i = 0; i < type_ignores.num_items; i++) { Ta3Node_AddChild(ch, TYPE_IGNORE, NULL, type_ignores.items[i], 0); } } growable_int_array_deallocate(&type_ignores); #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; Ta3Node_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif Ta3Parser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = Ta3Node_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: Ta3Tokenizer_Free(tok); return n; } static int initerr(perrdetail *err_ret, PyObject *filename) { err_ret->error = E_OK; err_ret->lineno = 0; err_ret->offset = 0; err_ret->text = NULL; err_ret->token = -1; err_ret->expected = -1; #ifndef PGEN if (filename) { Py_INCREF(filename); err_ret->filename = filename; } else { err_ret->filename = PyUnicode_FromString("<string>"); if (err_ret->filename == NULL) { err_ret->error = E_ERROR; return -1; } } #endif return 0; }
parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; growable_int_array type_ignores; if (!growable_int_array_init(&type_ignores, 10)) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } if ((ps = Ta3Parser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; int col_offset; type = Ta3Tokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = b - a; /* XXX this may compute NULL - NULL */ str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->text = "with Barry as BDFL, use '<>' " "instead of '!='"; err_ret->error = E_SYNTAX; break; } } #endif if (a >= tok->line_start) col_offset = Py_SAFE_DOWNCAST(a - tok->line_start, intptr_t, int); else col_offset = -1; if (type == TYPE_IGNORE) { if (!growable_int_array_add(&type_ignores, tok->lineno)) { err_ret->error = E_NOMEM; break; } continue; } if ((err_ret->error = Ta3Parser_AddToken(ps, (int)type, str, tok->lineno, col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; if (n->n_type == file_input) { /* Put type_ignore nodes in the ENDMARKER of file_input. */ int num; node *ch; size_t i; num = NCH(n); ch = CHILD(n, num - 1); REQ(ch, ENDMARKER); for (i = 0; i < type_ignores.num_items; i++) { Ta3Node_AddChild(ch, TYPE_IGNORE, NULL, type_ignores.items[i], 0); } } growable_int_array_deallocate(&type_ignores); #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; Ta3Node_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif Ta3Parser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = Ta3Node_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: Ta3Tokenizer_Free(tok); return n; }
parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; growable_int_array type_ignores; if (!growable_int_array_init(&type_ignores, 10)) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } if ((ps = Ta3Parser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; Ta3Tokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; int col_offset; type = Ta3Tokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = (a != NULL && b != NULL) ? b - a : 0; str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->expected = NOTEQUAL; err_ret->error = E_SYNTAX; break; } } #endif if (a != NULL && a >= tok->line_start) { col_offset = Py_SAFE_DOWNCAST(a - tok->line_start, intptr_t, int); } else { col_offset = -1; } if (type == TYPE_IGNORE) { if (!growable_int_array_add(&type_ignores, tok->lineno)) { err_ret->error = E_NOMEM; break; } continue; } if ((err_ret->error = Ta3Parser_AddToken(ps, (int)type, str, tok->lineno, col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; if (n->n_type == file_input) { /* Put type_ignore nodes in the ENDMARKER of file_input. */ int num; node *ch; size_t i; num = NCH(n); ch = CHILD(n, num - 1); REQ(ch, ENDMARKER); for (i = 0; i < type_ignores.num_items; i++) { Ta3Node_AddChild(ch, TYPE_IGNORE, NULL, type_ignores.items[i], 0); } } growable_int_array_deallocate(&type_ignores); #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; Ta3Node_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif Ta3Parser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = Ta3Node_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: Ta3Tokenizer_Free(tok); return n; }
{'added': [(67, ' if (*flags & PyPARSE_ASYNC_ALWAYS)'), (68, ' tok->async_always = 1;'), (269, ' len = (a != NULL && b != NULL) ? b - a : 0;'), (290, ' err_ret->expected = NOTEQUAL;'), (296, ' if (a != NULL && a >= tok->line_start) {'), (299, ' }'), (300, ' else {'), (302, ' }')], 'deleted': [(267, ' len = b - a; /* XXX this may compute NULL - NULL */'), (288, ' err_ret->text = "with Barry as BDFL, use \'<>\' "'), (289, ' "instead of \'!=\'";'), (295, ' if (a >= tok->line_start)'), (298, ' else')]}
8
5
354
2,117
https://github.com/python/typed_ast
CVE-2019-19274
['CWE-125']
migrate.c
migrate_page_copy
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ __dec_zone_page_state(page, NR_FILE_PAGES); __inc_zone_page_state(newpage, NR_FILE_PAGES); if (!PageSwapCache(page) && PageSwapBacked(page)) { __dec_zone_page_state(page, NR_SHMEM); __inc_zone_page_state(newpage, NR_SHMEM); } spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/backing-dev.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_zone_state(oldzone, NR_FILE_PAGES); __inc_zone_state(newzone, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_zone_state(oldzone, NR_SHMEM); __inc_zone_state(newzone, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_zone_state(oldzone, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_FILE_DIRTY); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); }
void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); }
{'added': [(33, '#include <linux/backing-dev.h>'), (317, '\tstruct zone *oldzone, *newzone;'), (318, '\tint dirty;'), (337, '\toldzone = page_zone(page);'), (338, '\tnewzone = page_zone(newpage);'), (339, ''), (387, '\t/* Move dirty while page refs frozen and newpage not yet exposed */'), (388, '\tdirty = PageDirty(page);'), (389, '\tif (dirty) {'), (390, '\t\tClearPageDirty(page);'), (391, '\t\tSetPageDirty(newpage);'), (392, '\t}'), (393, ''), (403, '\tspin_unlock(&mapping->tree_lock);'), (404, '\t/* Leave irq disabled to prevent preemption while updating stats */'), (405, ''), (416, '\tif (newzone != oldzone) {'), (417, '\t\t__dec_zone_state(oldzone, NR_FILE_PAGES);'), (418, '\t\t__inc_zone_state(newzone, NR_FILE_PAGES);'), (419, '\t\tif (PageSwapBacked(page) && !PageSwapCache(page)) {'), (420, '\t\t\t__dec_zone_state(oldzone, NR_SHMEM);'), (421, '\t\t\t__inc_zone_state(newzone, NR_SHMEM);'), (422, '\t\t}'), (423, '\t\tif (dirty && mapping_cap_account_dirty(mapping)) {'), (424, '\t\t\t__dec_zone_state(oldzone, NR_FILE_DIRTY);'), (425, '\t\t\t__inc_zone_state(newzone, NR_FILE_DIRTY);'), (426, '\t\t}'), (428, '\tlocal_irq_enable();'), (549, '\t/* Move dirty on pages not done by migrate_page_move_mapping() */'), (550, '\tif (PageDirty(page))'), (551, '\t\tSetPageDirty(newpage);')], 'deleted': [(400, '\t__dec_zone_page_state(page, NR_FILE_PAGES);'), (401, '\t__inc_zone_page_state(newpage, NR_FILE_PAGES);'), (402, '\tif (!PageSwapCache(page) && PageSwapBacked(page)) {'), (403, '\t\t__dec_zone_page_state(page, NR_SHMEM);'), (404, '\t\t__inc_zone_page_state(newpage, NR_SHMEM);'), (406, '\tspin_unlock_irq(&mapping->tree_lock);'), (527, '\tif (PageDirty(page)) {'), (528, '\t\tclear_page_dirty_for_io(page);'), (529, '\t\t/*'), (530, '\t\t * Want to mark the page and the radix tree as dirty, and'), (531, '\t\t * redo the accounting that clear_page_dirty_for_io undid,'), (532, "\t\t * but we can't use set_page_dirty because that function"), (533, '\t\t * is actually a signal that all of the page has become dirty.'), (534, '\t\t * Whereas only part of our page may be dirty.'), (535, '\t\t */'), (536, '\t\tif (PageSwapBacked(page))'), (537, '\t\t\tSetPageDirty(newpage);'), (538, '\t\telse'), (539, '\t\t\t__set_page_dirty_nobuffers(newpage);'), (540, ' \t}')]}
31
20
1,128
6,513
https://github.com/torvalds/linux
CVE-2016-3070
['CWE-476']
migrate.c
migrate_page_move_mapping
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ __dec_zone_page_state(page, NR_FILE_PAGES); __inc_zone_page_state(newpage, NR_FILE_PAGES); if (!PageSwapCache(page) && PageSwapBacked(page)) { __dec_zone_page_state(page, NR_SHMEM); __inc_zone_page_state(newpage, NR_SHMEM); } spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/backing-dev.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); if (unlikely(isolated_balloon_page(page))) balloon_page_putback(page); else putback_lru_page(page); } } /* * Restore a potential migration pte to a working pte entry */ static int remove_migration_pte(struct page *new, struct vm_area_struct *vma, unsigned long addr, void *old) { struct mm_struct *mm = vma->vm_mm; swp_entry_t entry; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; if (unlikely(PageHuge(new))) { ptep = huge_pte_offset(mm, addr); if (!ptep) goto out; ptl = huge_pte_lockptr(hstate_vma(vma), mm, ptep); } else { pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; ptep = pte_offset_map(pmd, addr); /* * Peek to check is_swap_pte() before taking ptlock? No, we * can race mremap's move_ptes(), which skips anon_vma lock. */ ptl = pte_lockptr(mm, pmd); } spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto unlock; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry) || migration_entry_to_page(entry) != old) goto unlock; get_page(new); pte = pte_mkold(mk_pte(new, vma->vm_page_prot)); if (pte_swp_soft_dirty(*ptep)) pte = pte_mksoft_dirty(pte); /* Recheck VMA as permissions can change since migration started */ if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); } #endif flush_dcache_page(new); set_pte_at(mm, addr, ptep, pte); if (PageHuge(new)) { if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, addr); else page_dup_rmap(new); } else if (PageAnon(new)) page_add_anon_rmap(new, vma, addr); else page_add_file_rmap(new); if (vma->vm_flags & VM_LOCKED) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, addr, ptep); unlock: pte_unmap_unlock(ptep, ptl); out: return SWAP_AGAIN; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ static void remove_migration_ptes(struct page *old, struct page *new) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_zone_state(oldzone, NR_FILE_PAGES); __inc_zone_state(newzone, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_zone_state(oldzone, NR_SHMEM); __inc_zone_state(newzone, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_zone_state(oldzone, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_FILE_DIRTY); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; } /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(pslot, newpage); page_unfreeze_refs(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems provide a * migratepage callback. Anonymous pages are part of swap * space which also has its own migratepage callback. This * is the most common path for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { set_page_memcg(page, NULL); if (!PageAnon(page)) page->mapping = NULL; } return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(isolated_balloon_page(page))) { /* * A ballooned page does not need any special attention from * physical to virtual reverse mapping procedures. * Skip any attempt to unmap PTEs or to remap swap cache, * in order to avoid burning cycles at rmap level, and perform * the page migration right away (proteced by page lock). */ rc = balloon_page_migrate(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ goto out; } if (unlikely(PageTransHuge(page))) if (unlikely(split_huge_page(page))) goto out; rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) put_new_page = NULL; out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); /* Soft-offlined page shouldn't go through lru cache list */ if (reason == MR_MEMORY_FAILURE) { put_page(page); if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } else putback_lru_page(page); } /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, putback_lru_page() will drop the reference grabbed * during isolation. */ if (put_new_page) put_new_page(newpage, private); else if (unlikely(__is_movable_balloon_page(newpage))) { /* drop our reference, page already in the balloon */ put_page(newpage); } else putback_lru_page(newpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; if (!zone_reclaimable(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~GFP_IOFS, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_zone_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; pmd_t orig_entry; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER); if (!new_page) goto out_fail; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } if (mm_tlb_flush_pending(mm)) flush_tlb_range(vma, mmun_start, mmun_end); /* Prepare a page as a migration target */ __set_page_locked(new_page); SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) { fail_putback: spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } orig_entry = *pmd; entry = mk_pmd(new_page, vma->vm_page_prot); entry = pmd_mkhuge(entry); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); flush_tlb_range(vma, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); if (page_count(page) != 2) { set_pmd_at(mm, mmun_start, pmd, orig_entry); flush_tlb_range(vma, mmun_start, mmun_end); mmu_notifier_invalidate_range(mm, mmun_start, mmun_end); update_mmu_cache_pmd(vma, address, &entry); page_remove_rmap(new_page); goto fail_putback; } mlock_migrate_page(new_page, page); set_page_memcg(new_page, page_memcg(page)); set_page_memcg(page, NULL); page_remove_rmap(page); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ __dec_zone_page_state(page, NR_FILE_PAGES); __inc_zone_page_state(newpage, NR_FILE_PAGES); if (!PageSwapCache(page) && PageSwapBacked(page)) { __dec_zone_page_state(page, NR_SHMEM); __inc_zone_page_state(newpage, NR_SHMEM); } spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; }
int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_freeze_refs(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_unfreeze_refs(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ set_page_memcg(newpage, page_memcg(page)); newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) SetPageSwapBacked(newpage); get_page(newpage); /* add cache reference */ if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_unfreeze_refs(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_PAGES if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_zone_state(oldzone, NR_FILE_PAGES); __inc_zone_state(newzone, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_zone_state(oldzone, NR_SHMEM); __inc_zone_state(newzone, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_zone_state(oldzone, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_FILE_DIRTY); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; }
{'added': [(33, '#include <linux/backing-dev.h>'), (317, '\tstruct zone *oldzone, *newzone;'), (318, '\tint dirty;'), (337, '\toldzone = page_zone(page);'), (338, '\tnewzone = page_zone(newpage);'), (339, ''), (387, '\t/* Move dirty while page refs frozen and newpage not yet exposed */'), (388, '\tdirty = PageDirty(page);'), (389, '\tif (dirty) {'), (390, '\t\tClearPageDirty(page);'), (391, '\t\tSetPageDirty(newpage);'), (392, '\t}'), (393, ''), (403, '\tspin_unlock(&mapping->tree_lock);'), (404, '\t/* Leave irq disabled to prevent preemption while updating stats */'), (405, ''), (416, '\tif (newzone != oldzone) {'), (417, '\t\t__dec_zone_state(oldzone, NR_FILE_PAGES);'), (418, '\t\t__inc_zone_state(newzone, NR_FILE_PAGES);'), (419, '\t\tif (PageSwapBacked(page) && !PageSwapCache(page)) {'), (420, '\t\t\t__dec_zone_state(oldzone, NR_SHMEM);'), (421, '\t\t\t__inc_zone_state(newzone, NR_SHMEM);'), (422, '\t\t}'), (423, '\t\tif (dirty && mapping_cap_account_dirty(mapping)) {'), (424, '\t\t\t__dec_zone_state(oldzone, NR_FILE_DIRTY);'), (425, '\t\t\t__inc_zone_state(newzone, NR_FILE_DIRTY);'), (426, '\t\t}'), (428, '\tlocal_irq_enable();'), (549, '\t/* Move dirty on pages not done by migrate_page_move_mapping() */'), (550, '\tif (PageDirty(page))'), (551, '\t\tSetPageDirty(newpage);')], 'deleted': [(400, '\t__dec_zone_page_state(page, NR_FILE_PAGES);'), (401, '\t__inc_zone_page_state(newpage, NR_FILE_PAGES);'), (402, '\tif (!PageSwapCache(page) && PageSwapBacked(page)) {'), (403, '\t\t__dec_zone_page_state(page, NR_SHMEM);'), (404, '\t\t__inc_zone_page_state(newpage, NR_SHMEM);'), (406, '\tspin_unlock_irq(&mapping->tree_lock);'), (527, '\tif (PageDirty(page)) {'), (528, '\t\tclear_page_dirty_for_io(page);'), (529, '\t\t/*'), (530, '\t\t * Want to mark the page and the radix tree as dirty, and'), (531, '\t\t * redo the accounting that clear_page_dirty_for_io undid,'), (532, "\t\t * but we can't use set_page_dirty because that function"), (533, '\t\t * is actually a signal that all of the page has become dirty.'), (534, '\t\t * Whereas only part of our page may be dirty.'), (535, '\t\t */'), (536, '\t\tif (PageSwapBacked(page))'), (537, '\t\t\tSetPageDirty(newpage);'), (538, '\t\telse'), (539, '\t\t\t__set_page_dirty_nobuffers(newpage);'), (540, ' \t}')]}
31
20
1,128
6,513
https://github.com/torvalds/linux
CVE-2016-3070
['CWE-476']
jsiArray.c
Jsi_ValueArrayShift
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); }
void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayConcatCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; }
static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayFillCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; }
static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayFilterCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; }
static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayFlatSub
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; }
static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayIndexSubCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; }
static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayJoinCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; }
static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayMapCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; }
static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayPopCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; }
static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayPushCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; }
static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayReduceSubCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; }
static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayShiftCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; }
static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArraySizeOfCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; }
static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArraySliceCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; }
static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
jsiArray.c
jsi_ArrayUnshiftCmd
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = Jsi_ObjGetLength(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = Jsi_ObjGetLength(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = Jsi_ObjGetLength(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = Jsi_ObjGetLength(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; int curlen; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; int curlen; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int curlen, i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) Jsi_ObjSetLength(interp, obj, 0); Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = Jsi_ObjGetLength(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = Jsi_ObjGetLength(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = Jsi_ObjGetLength(interp, obj); assert(n <= obj->arrCnt); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = Jsi_ObjGetLength(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = Jsi_ObjGetLength(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
#ifndef JSI_LITE_ONLY #ifndef JSI_AMALGAMATION #include "jsiInt.h" #endif #if JSI__MUSL==1 || defined(__FreeBSD__) #define NO_QSORT_R 1 #endif static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) { if (!obj || !obj->arr) return 0; return obj->arrCnt; } static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { Jsi_Obj *obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); } Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0); } Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayPopCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_Value *v; Jsi_Obj *obj; obj = _this->d.obj; int i = jsi_SizeOfArray(interp, obj) - 1; if (i < 0) { Jsi_ValueMakeUndef(interp, ret); return JSI_OK; } if (obj->arr) { if ((v = obj->arr[i])) { obj->arr[i] = NULL; obj->arrCnt--; } } else { v = Jsi_ValueArrayIndex(interp, _this, i); } if (v) { Jsi_DecrRefCount(interp, *ret); *ret = v; } Jsi_ObjSetLength(interp, obj, i); return JSI_OK; } static Jsi_RC jsi_ArrayJoinCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); const char *jstr = ""; int argc, curlen; Jsi_DString dStr = {}; curlen = jsi_SizeOfArray(interp, _this->d.obj); if (curlen == 0) { goto bail; } if (Jsi_ValueGetLength(interp, args) >= 1) { Jsi_Value *sc = Jsi_ValueArrayIndex(interp, args, 0); if (sc != NULL) jstr = Jsi_ValueToString(interp, sc, NULL); } if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) { goto bail; } int i; for (i = 0; i < argc; ++i) { const char *cp; Jsi_Value *ov = Jsi_ValueArrayIndex(interp, _this, i); if (!ov) { /* TODO: are NULL args ok? */ continue; cp = ""; } else cp = Jsi_ValueToString(interp, ov, NULL); if (i && jstr[0]) Jsi_DSAppend(&dStr, jstr, NULL); Jsi_DSAppend(&dStr, cp, NULL); } Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(&dStr)); Jsi_DSFree(&dStr); return JSI_OK; bail: Jsi_ValueMakeStringDup(interp, ret, ""); return JSI_OK; } Jsi_Value* Jsi_ValueArrayConcat(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Value *va; Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) { return NULL; } if (arg2->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg2->d.obj)) { return NULL; } int len1 = arg1->d.obj->arrCnt; int len2 = arg2->d.obj->arrCnt; Jsi_Obj *nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ObjArraySizer(interp, nobj, len1+len2); int i, j = 0; obj = arg1->d.obj; for (i = 0; i<len1; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } obj = arg2->d.obj; for (i = 0; i<len2; i++, j++) { if (!obj->arr[i]) continue; nobj->arr[j] = NULL; Jsi_ValueDup2(interp, nobj->arr+j, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, len1+len2); va = Jsi_ValueMakeArrayObject(interp, NULL, nobj); return va; } Jsi_RC Jsi_ValueArrayPush(Jsi_Interp *interp, Jsi_Value *arg1, Jsi_Value *arg2) { Jsi_Obj *obj; if (arg1->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, arg1->d.obj)) return JSI_ERROR; if (!arg2) return JSI_ERROR; int len1 = arg1->d.obj->arrCnt; obj = arg1->d.obj; Jsi_ObjArraySizer(interp, obj, len1); obj->arr[len1] = arg2; Jsi_IncrRefCount(interp, arg2); obj->arrCnt++; return JSI_OK; } Jsi_Value *Jsi_ValueArrayPop(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayPop, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayPop, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; int idx = o->arrCnt-1; if (!o->arr[idx]) return NULL; Jsi_DecrRefCount(interp, o->arr[idx]); Jsi_Value *ret = o->arr[idx]; o->arr[idx] = NULL; o->arrCnt--; return ret; } Jsi_Value *Jsi_ValueArrayUnshift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not object"); return NULL; } Jsi_Obj *o = v->d.obj; if (!o->isarrlist) { Jsi_LogBug("Jsi_ValueArrayUnshift, target is not array"); return NULL; } if (o->arrCnt<=0) return NULL; if (!o->arr[0]) return NULL; Jsi_DecrRefCount(interp, o->arr[0]); Jsi_Value *ret = o->arr[0]; o->arr[0] = NULL; o->arrCnt--; return ret; } /* delete array[0], array[1]->array[0] */ void Jsi_ValueArrayShift(Jsi_Interp *interp, Jsi_Value *v) { if (v->vt != JSI_VT_OBJECT) { Jsi_LogBug("Jsi_ValueArrayShift, target is not object"); return; } Jsi_Obj *o = v->d.obj; if (o->isarrlist) { uint i; if (!o->arrCnt) return; if (o->arr[0]) Jsi_DecrRefCount(interp, o->arr[0]); for (i=1; i<o->arrCnt; i++) { o->arr[i-1] = o->arr[i]; } o->arr[o->arrCnt--] = NULL; return; } int len = jsi_SizeOfArray(interp, v->d.obj); if (len <= 0) return; Jsi_Value *v0 = Jsi_ValueArrayIndex(interp, v, 0); if (!v0) return; Jsi_ValueReset(interp, &v0); int i; Jsi_Value *last = v0; for (i = 1; i < len; ++i) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, v, i); if (!t) return; Jsi_ValueCopy(interp, last, t); Jsi_ValueReset(interp, &t); last = t; } Jsi_ObjSetLength(interp, v->d.obj, len - 1); } static Jsi_RC jsi_ArrayFlatSub(Jsi_Interp *interp, Jsi_Obj* nobj, Jsi_Value *arr, int depth) { int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj); if (len <= 0) return JSI_OK; Jsi_RC rc = JSI_OK; int clen = jsi_SizeOfArray(interp, nobj); for (i = 0; i < len && rc == JSI_OK; i++) { Jsi_Value *t = Jsi_ValueArrayIndex(interp, arr, i); if (t && depth>0 && Jsi_ValueIsArray(interp, t)) rc = jsi_ArrayFlatSub(interp, nobj, t , depth-1); else if (!Jsi_ValueIsUndef(interp, t)) Jsi_ObjArrayAdd(interp, nobj, t); if ((++n + clen)>interp->maxArrayList) return Jsi_LogError("array size exceeded"); } return rc; } static Jsi_RC jsi_ArrayFlatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Number ndepth = 1; Jsi_Obj *nobj; Jsi_Value *depth = Jsi_ValueArrayIndex(interp, args, 0); if (depth && Jsi_GetNumberFromValue(interp,depth, &ndepth) != JSI_OK) return JSI_ERROR; if (ndepth < 0 || ndepth>1000) return Jsi_LogError("bad depth: %d", (int)ndepth); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj ); if (ndepth>0) return jsi_ArrayFlatSub(interp, nobj, _this, ndepth); return JSI_OK; } static Jsi_RC jsi_ArrayConcatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, argc, nsiz; Jsi_Obj *obj, *nobj; Jsi_Value *va; obj = _this->d.obj; argc = Jsi_ValueGetLength(interp, args); curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrMaxSize; if (nsiz<=0) nsiz = 100; if (Jsi_ObjArraySizer(interp, nobj, nsiz+1) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", nsiz+1); goto bail; } int i, j, m; for (i = 0; i<curlen; i++) { if (!obj->arr[i]) continue; nobj->arr[i] = NULL; Jsi_ValueDup2(interp, nobj->arr+i, obj->arr[i]); } m = i; for (i = 0; i < argc; i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (va->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, va->d.obj)) { int margc = Jsi_ValueGetLength(interp, va); Jsi_Obj *mobj = va->d.obj; Jsi_ObjListifyArray(interp, mobj); if (Jsi_ObjArraySizer(interp, nobj, curlen += margc) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } for (j = 0; j<margc; j++, m++) { if (!mobj->arr[j]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, mobj->arr[j]); } } else { if (Jsi_ObjArraySizer(interp, nobj, ++curlen) <= 0) { rc = JSI_ERROR; Jsi_LogError("index too large: %d", curlen); goto bail; } nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m++, va); } } Jsi_ObjSetLength(interp, nobj, curlen); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayMapCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_Value *vobjs[3]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); nobj->arr[i] = Jsi_ValueNew1(interp); rc = Jsi_FunctionInvoke(interp, func, vpargs, nobj->arr+i, sthis); Jsi_DecrRefCount(interp, vpargs); if( JSI_OK!=rc ) { goto bail; } } Jsi_ObjSetLength(interp, nobj, curlen); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFilterCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int curlen, nsiz, i, fval, n = 0, maa = 0; Jsi_Obj *obj, *nobj; Jsi_Value *func, *vpargs, *nthis = NULL, *sthis, *nrPtr = NULL; Jsi_Func *fptr = NULL; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; curlen = jsi_SizeOfArray(interp, obj); Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); nsiz = obj->arrCnt; if (nsiz<=0) nsiz = 1; if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { Jsi_LogError("index too large: %d", nsiz); rc = JSI_ERROR; goto bail; } Jsi_ValueMakeArrayObject(interp, ret, nobj); nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[4]; fptr = func->d.obj->d.fobj->func; maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < curlen; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if( JSI_OK!=rc ) { goto bail; } if (fval) { nobj->arr[n++] = obj->arr[i]; Jsi_IncrRefCount(interp, obj->arr[i]); } } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); Jsi_ObjSetLength(interp, nobj, n); return JSI_OK; bail: if (nthis) Jsi_DecrRefCount(interp, nthis); if (nrPtr) Jsi_DecrRefCount(interp, nrPtr); Jsi_ValueMakeNull(interp, ret); return rc; } static Jsi_RC jsi_ArrayReverseCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); int i, n, m; Jsi_Obj *obj; Jsi_Value *tval, *nthis = NULL, *sthis = Jsi_ValueArrayIndex(interp, args, 1); if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); m = obj->arrCnt/2; for (i = 0, n=obj->arrCnt-1; i < m; i++, n--) { tval = obj->arr[i]; obj->arr[i] = obj->arr[n]; obj->arr[n] = tval; } Jsi_ValueDup2(interp, ret, _this); if (nthis) Jsi_DecrRefCount(interp, nthis); return JSI_OK; } static Jsi_RC jsi_ArrayForeachCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj; uint i; Jsi_Value *func, *vpargs; func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *sthis = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_RC rc = JSI_OK; Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, ret, sthis); Jsi_DecrRefCount(interp, vpargs); } if (nthis) Jsi_DecrRefCount(interp, nthis); return rc; } static Jsi_RC jsi_ArrayFindSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_Obj *obj; uint i; Jsi_RC rc = JSI_OK; Jsi_Value *func, *vpargs, *sthis = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nthis = NULL; if (!sthis) sthis = nthis = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); int fval = 0; Jsi_Value *nrPtr = Jsi_ValueNew1(interp); Jsi_Value *vobjs[3]; Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>3) maa = 3; for (i = 0; i < obj->arrCnt && rc == JSI_OK; i++) { if (!obj->arr[i]) continue; vobjs[0] = obj->arr[i]; vobjs[1] = (maa>1?Jsi_ValueNewNumber(interp, i):NULL); vobjs[2] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, sthis); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; fval = Jsi_ValueIsTrue(interp, nrPtr); Jsi_ValueMakeUndef(interp, &nrPtr); if (op == 3) { if (!fval) break; } else if (fval) break; } if (rc == JSI_OK) { if (op == 1 && fval) // Find Jsi_ValueCopy(interp, *ret, obj->arr[i]); else if (op == 2 || op == 3) // Some/Every Jsi_ValueMakeBool(interp, ret, fval); else if (op == 4) Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)(fval?(int)i:-1)); } if (nthis) Jsi_DecrRefCount(interp, nthis); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayReduceSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array"); Jsi_RC rc = JSI_OK; int i; Jsi_Obj *obj; Jsi_Value *func, *vpargs, *ini = Jsi_ValueArrayIndex(interp, args, 1); func = Jsi_ValueArrayIndex(interp, args, 0); if (!Jsi_ValueIsFunction(interp, func)) return Jsi_LogError("expected function"); Jsi_Value *nrPtr = Jsi_ValueNew1(interp); obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); Jsi_Value *vobjs[4]; int n, rev = (op==2); Jsi_Func *fptr = func->d.obj->d.fobj->func; int maa = (fptr->argnames?fptr->argnames->argCnt:0); if (maa>4) maa = 4; for (n = 0, i = (rev?obj->arrCnt-1:0); (rev?i>=0:i < (int)obj->arrCnt) && rc == JSI_OK; n++, i = (rev?i-1:i+1)) { if (!obj->arr[i]) continue; if (n==0 && !ini) { ini = obj->arr[i]; continue; } vobjs[0] = ini; vobjs[1] = obj->arr[i]; vobjs[2] = (maa>2?Jsi_ValueNewNumber(interp, i):NULL); vobjs[3] = _this; vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vobjs, maa, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, func, vpargs, &nrPtr, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc != JSI_OK) break; ini = nrPtr; } if (rc == JSI_OK && ini) Jsi_ValueCopy(interp, *ret, ini); Jsi_DecrRefCount(interp, nrPtr); return rc; } static Jsi_RC jsi_ArrayFindCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArraySomeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayEveryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArrayFindIndexCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayFindSubCmd(interp, args, _this, ret, funcPtr, 4); } static Jsi_RC jsi_ArrayReduceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayReduceRightCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayReduceSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIsArrayCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { bool b = 0; Jsi_Value *sthis = _this; if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && _this->d.obj->__proto__ == interp->Array_prototype->d.obj->__proto__ ) sthis = Jsi_ValueArrayIndex(interp, args, 0); if (sthis && sthis->vt == JSI_VT_OBJECT && Jsi_ObjIsArray(interp, sthis->d.obj)) b = 1; Jsi_ValueMakeBool(interp, ret, b); return JSI_OK; } static Jsi_RC jsi_ArrayIndexSubCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr, int op) { int istart = 0, n, i = 0, dir=1, idx=-1; Jsi_Value *seq = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1); Jsi_Obj *obj = _this->d.obj; if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); if (!seq) { goto bail; } n = jsi_SizeOfArray(interp, obj); if (n == 0) { goto bail; } Jsi_Number nstart; if (op == 2) { istart = n-1; } if (start && Jsi_GetNumberFromValue(interp,start, &nstart)==JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (op == 2) { istart = n-1; dir = -1; } Jsi_ObjListifyArray(interp, obj); for (i = istart; ; i+=dir) { if ((dir>0 && i>=n) || (dir<0 && i<0) || i>=(int)obj->arrCnt) break; if (obj->arr[i] && Jsi_ValueCmp(interp, obj->arr[i], seq, JSI_CMP_EXACT)==0) { idx = i; break; } } bail: if (op == 3) Jsi_ValueMakeBool(interp, ret, (idx!=-1)); else Jsi_ValueMakeNumber(interp, ret, idx); return JSI_OK; } static Jsi_RC jsi_ArrayIndexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 1); } static Jsi_RC jsi_ArrayLastindexOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 2); } static Jsi_RC jsi_ArrayIncludesCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { return jsi_ArrayIndexSubCmd(interp, args, _this, ret, funcPtr, 3); } static Jsi_RC jsi_ArraySizeOfCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int i = jsi_SizeOfArray(interp, _this->d.obj); Jsi_ValueMakeNumber(interp, ret, i); return JSI_OK; } static Jsi_RC jsi_ArrayShiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Value *v; Jsi_Obj *obj = _this->d.obj; Jsi_ObjListifyArray(interp, obj); uint n = jsi_SizeOfArray(interp, obj); if (n<=0) { Jsi_ValueMakeUndef(interp, ret); } else { n--; v = obj->arr[0]; memmove(obj->arr, obj->arr+1, n*sizeof(Jsi_Value*)); obj->arr[n] = NULL; Jsi_ValueDup2(interp, ret, v); Jsi_DecrRefCount(interp, v); Jsi_ObjSetLength(interp, obj, n); } return JSI_OK; } static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; } static Jsi_RC jsi_ArrayFillCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart = 0, nend = 0; // TODO: merge with code in ArraySliceCmd. Jsi_Value *value = Jsi_ValueArrayIndex(interp, args, 0), *start = Jsi_ValueArrayIndex(interp, args, 1), *end = Jsi_ValueArrayIndex(interp, args, 2); Jsi_Obj *obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (start && Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { goto bail; } iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto bail; int i; for (i = istart; i <= iend; i++) { if (obj->arr[i]) Jsi_ValueCopy(interp, obj->arr[i], value); else obj->arr[i] = Jsi_ValueDup(interp, value); } bail: if (_this != *ret) { Jsi_ValueMove(interp, *ret, _this); /*if (*ret) Jsi_DecrRefCount(interp, *ret); *ret = _this; Jsi_IncrRefCount(interp, *ret);*/ } return rc; } static Jsi_RC jsi_ArraySliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_RC rc = JSI_OK; int istart = 0, iend, n, nsiz; Jsi_Number nstart; Jsi_Obj *nobj, *obj; Jsi_Value *start = Jsi_ValueArrayIndex(interp, args, 0), *end = Jsi_ValueArrayIndex(interp, args, 1); if (!start) { goto bail; } obj = _this->d.obj; n = jsi_SizeOfArray(interp, obj); if (Jsi_GetNumberFromValue(interp,start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto done; if (istart < 0) istart = (n+istart); if (istart<0) goto bail; } if (n == 0) { done: Jsi_ValueMakeArrayObject(interp, ret, Jsi_ObjNewType(interp, JSI_OT_ARRAY)); return JSI_OK; } Jsi_Number nend; iend = n-1; if (end && Jsi_GetNumberFromValue(interp,end, &nend) == JSI_OK) { iend = (int) nend; if (iend >= n) iend = n; if (iend < 0) iend = (n+iend); if (iend<0) goto bail; } nsiz = iend-istart+1; if (nsiz<=0) goto done; Jsi_ObjListifyArray(interp, obj); nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); if (Jsi_ObjArraySizer(interp, nobj, nsiz) <= 0) { rc = Jsi_LogError("index too large: %d", nsiz); goto bail; } int i, m; for (m = 0, i = istart; i <= iend; i++, m++) { if (!obj->arr[i]) continue; nobj->arr[m] = NULL; Jsi_ValueDup2(interp, nobj->arr+m, obj->arr[i]); } Jsi_ObjSetLength(interp, nobj, nsiz); Jsi_ValueMakeArrayObject(interp, ret, nobj); return JSI_OK; bail: Jsi_ValueMakeNull(interp, ret); return rc; } typedef struct { Jsi_Interp *interp; int flags; int mode; bool unique; Jsi_Value *compare; int errCnt; } SortInfo; static const char *sortArrayStrs[] = {"default", "desc", "dict", "nocase", 0}; static Jsi_OptionSpec jsi_ArraySortOptions[] = { JSI_OPT(CUSTOM, SortInfo, mode, .help="Mode to sort by", .flags=0, .custom=Jsi_Opt_SwitchEnum, .data=sortArrayStrs), JSI_OPT(FUNC, SortInfo, compare, .help="Function to do comparison", .flags=0, .custom=0, .data=(void*)"val1,val2"), JSI_OPT(BOOL, SortInfo, unique, .help="Eliminate duplicate items"), JSI_OPT_END(SortInfo) }; #ifdef NO_QSORT_R SortInfo *curSortInfo = NULL; static int SortSubCmd(const void *p1, const void *p2) { SortInfo *si = curSortInfo; #else #ifdef __WIN32 static int SortSubCmd(void *thunk, const void *p1, const void *p2) #else static int SortSubCmd(const void *p1, const void *p2, void *thunk) #endif { SortInfo *si = (SortInfo *)thunk; #endif Jsi_Interp *interp = si->interp; int sortFlags = si->flags; if (interp == NULL || interp->deleting) return 0; Jsi_Value *v1 = *(Jsi_Value**)p1, *v2 = *(Jsi_Value**)p2; int rc = 0; if (v1 != NULL && v2 != NULL) { VALCHK(v1); VALCHK(v2); if (!si->compare) rc = Jsi_ValueCmp(interp, v1, v2, sortFlags); else { Jsi_Value *vv[2] = {v1, v2}; Jsi_Value *retP = Jsi_ValueNew1(interp); Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, vv, 2, 0)); Jsi_IncrRefCount(interp, vpargs); rc = Jsi_FunctionInvoke(interp, si->compare, vpargs, &retP, NULL); Jsi_DecrRefCount(interp, vpargs); if (rc == JSI_OK) { Jsi_Number d = 0; if (Jsi_ValueGetNumber(interp, retP, &d) == JSI_OK) rc = -(int)d; else { if (!si->errCnt) Jsi_LogWarn("invalid function return"); si->errCnt++; } } Jsi_DecrRefCount(interp, retP); } } else { if (v1 == v2) rc = 0; else if (v1 == NULL) rc = 1; else rc = -1; } if ((sortFlags&JSI_SORT_DESCEND)) return rc; return -rc; } Jsi_RC Jsi_ValueArraySort(Jsi_Interp *interp, Jsi_Value *val, int flags) { if (val->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, val->d.obj)) { return JSI_ERROR; } Jsi_Obj *obj = val->d.obj; Jsi_ObjListifyArray(interp, obj); if (obj->arrCnt <= 0) { return JSI_OK; } #ifdef __WIN32 #define qsort_r qsort_s #endif SortInfo si = {}; si.interp = interp; si.flags = flags; #ifdef NO_QSORT_R curSortInfo = &si; qsort(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd); curSortInfo = NULL; #else qsort_r(obj->arr, obj->arrCnt, sizeof(Jsi_Value*), SortSubCmd, &si); #endif return JSI_OK; } static Jsi_RC jsi_ArraySortCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int flags = 0, i, curlen, hasopt = 0; Jsi_Value *v, *arg = NULL; SortInfo si = {}; si.interp = interp; Jsi_Obj *obj = _this->d.obj; curlen = obj->arrCnt; if (curlen <= 1) { goto done; } arg = Jsi_ValueArrayIndex(interp, args, 0); if (arg) { if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) { if (Jsi_OptionsProcess(interp, jsi_ArraySortOptions, &si, arg, 0) < 0) return JSI_ERROR; hasopt = 1; switch (si.mode) { case 1: flags |= JSI_SORT_DESCEND; break; case 2: flags |= JSI_SORT_DICT; break; case 3: flags |= JSI_SORT_NOCASE; break; } } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_FUNCTION)) si.compare = arg; else return Jsi_LogError("expected object or function"); } si.flags = flags; Jsi_ObjListifyArray(interp, obj); #ifdef NO_QSORT_R /* TODO: mutex. */ curSortInfo = &si; qsort(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd); #else qsort_r(obj->arr, curlen, sizeof(Jsi_Value*), SortSubCmd, &si); #endif if (interp->deleting) { #ifdef NO_QSORT_R curSortInfo = NULL; #endif return JSI_ERROR; } if (si.unique) { int n, diff = 1, dupCnt=0; for (n=0, i=1; i<(int)obj->arrCnt; i++) { if (obj->arr[n] == obj->arr[i]) diff = 1; else #ifdef NO_QSORT_R diff = SortSubCmd(&obj->arr[n], &obj->arr[i]); #else #ifdef __WIN32 diff = SortSubCmd(&si, &obj->arr[n], &obj->arr[i]); #else diff = SortSubCmd(&obj->arr[n], &obj->arr[i], &si); #endif #endif if (diff) { n++; if (n!=i) obj->arr[n] = obj->arr[i]; } else { dupCnt++; if (obj->arr[i]) Jsi_DecrRefCount(interp, obj->arr[i]); obj->arr[i] = 0; } } obj->arrCnt -= dupCnt; } #ifdef NO_QSORT_R curSortInfo = NULL; #endif if (hasopt) Jsi_OptionsFree(interp, jsi_ArraySortOptions, &si, 0); done: v = Jsi_ValueMakeObject(interp, NULL, obj); Jsi_ValueReplace(interp, ret, v); return JSI_OK; Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArraySpliceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); int newlen, argc, istart, n, rhowmany, ilen, curlen; Jsi_Value *va, *start, *howmany; Jsi_Obj *nobj, *obj = _this->d.obj; start = Jsi_ValueArrayIndex(interp, args, 0); howmany = Jsi_ValueArrayIndex(interp, args, 1); argc = Jsi_ValueGetLength(interp, args); istart = 0; ilen = (argc>=2 ? argc - 2 : 0); n = jsi_SizeOfArray(interp, obj); curlen = n; if (!start) { goto bail2; } nobj = Jsi_ObjNewType(interp, JSI_OT_ARRAY); Jsi_ValueMakeArrayObject(interp, ret, nobj); Jsi_ObjSetLength(interp, nobj, 0); /* Determine start index. */ Jsi_Number nstart; if (Jsi_GetNumberFromValue(interp, start, &nstart) == JSI_OK) { istart = (int)nstart; if (istart > n) goto bail; if (istart < 0) istart = (n+istart); if (istart<0) istart=0; } Jsi_Number nhow; rhowmany = n-istart; if (howmany && Jsi_GetNumberFromValue(interp, howmany, &nhow) == JSI_OK) { rhowmany = (int)nhow; if (rhowmany >= (n-istart)) rhowmany = n-istart; if (rhowmany < 0) rhowmany = (n-istart); if (rhowmany<0) goto bail; } if (curlen < 0) { Jsi_ObjSetLength(interp, obj, curlen=0); } Jsi_ObjListifyArray(interp, obj); Jsi_ObjArraySizer(interp, nobj, rhowmany); /* Move elements to return object. */ int i, j, m; for (m=0, j = 0, i = istart; m<rhowmany && m<curlen; m++, i++, j++) { if (!obj->arr[i]) continue; nobj->arr[m] = obj->arr[i]; obj->arr[i] = NULL; } Jsi_ObjSetLength(interp, nobj, m); /* Shift remaining down. */ for (; rhowmany && i<curlen; i++) { obj->arr[i-rhowmany] = obj->arr[i]; obj->arr[i] = NULL; } curlen -= j; /* Add elements. */ newlen = curlen + argc - (argc>=2?2:1); if (Jsi_ObjArraySizer(interp, obj, newlen+3) <= 0) { Jsi_LogError("too long"); Jsi_ValueMakeUndef(interp, ret); return JSI_ERROR; } if (ilen>0) { for (i = curlen-1; i>=istart; i--) { obj->arr[i+ilen] = obj->arr[i]; obj->arr[i] = NULL; } for (m=istart, i = 2; i<argc; m++,i++) { va = Jsi_ValueArrayIndex(interp, args, i); if (!va) continue; obj->arr[m] = NULL; Jsi_ValueDup2(interp, obj->arr+m, va); } } Jsi_ObjSetLength(interp, obj, newlen); bail: return JSI_OK; bail2: Jsi_ValueMakeNull(interp, ret); return JSI_OK; } static Jsi_RC jsi_ArrayConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr) { int argc = Jsi_ValueGetLength(interp, args), iscons = Jsi_FunctionIsConstructor(funcPtr); Jsi_Value *target; Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0); if (iscons) { target = _this; Jsi_ValueMakeArrayObject(interp, &_this, Jsi_ObjNewArray(interp, NULL, 0, 0)); } else { Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY); o->__proto__ = interp->Array_prototype; Jsi_ValueMakeObject(interp, ret, o); target = *ret; } if (argc == 1 && v && Jsi_ValueIsNumber(interp, v)) { Jsi_Number nv; Jsi_GetNumberFromValue(interp,v, &nv); int len = (int)nv; if (!Jsi_NumberIsInteger(v->d.num) || len < 0) return Jsi_LogError("Invalid array length"); target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, len) <= 0) return JSI_ERROR; } else { int i; target->d.obj->isarrlist = 1; if (Jsi_ObjArraySizer(interp, target->d.obj, 0) <= 0) return JSI_ERROR; for (i = 0; i < argc; ++i) { Jsi_Value *argv = Jsi_ValueArrayIndex(interp, args, i); ; Jsi_ValueInsertArray(interp, _this, i, argv, 0); } } if (iscons) Jsi_ValueDup2(interp, ret, target); return JSI_OK; } static Jsi_CmdSpec arrayCmds[] = { { "Array", jsi_ArrayConstructor, 0,-1, "...", .help="jsi_Array constructor", .retType=(uint)JSI_TT_ARRAY, .flags=JSI_CMD_IS_CONSTRUCTOR }, { "concat", jsi_ArrayConcatCmd, 0,-1, "...", .help="Return array with args appended", .retType=(uint)JSI_TT_ARRAY }, { "every", jsi_ArrayEveryCmd, 1, 1, "callback:function", .help="Returns true if every value in array satisfies the test", .retType=(uint)JSI_TT_ANY }, { "fill", jsi_ArrayFillCmd, 1, 3, "value:any, start:number=0, end:number=-1", .help="Fill an array with values", .retType=(uint)JSI_TT_ARRAY }, { "filter", jsi_ArrayFilterCmd, 1, 2, "callback:function, this:object=void", .help="Return a filtered array", .retType=(uint)JSI_TT_ARRAY }, { "find", jsi_ArrayFindCmd, 1, 1, "callback:function", .help="Returns the value of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "findIndex", jsi_ArrayFindIndexCmd, 1, 1, "callback:function", .help="Returns the index of the first element in the array that satisfies the test", .retType=(uint)JSI_TT_ANY }, { "flat", jsi_ArrayFlatCmd, 0, 1, "depth:number=1", .help="Flatten an arra", .retType=(uint)JSI_TT_ARRAY }, { "forEach", jsi_ArrayForeachCmd, 1, 2, "callback:function, this:object=void", .help="Invoke function with each item in object", .retType=(uint)JSI_TT_VOID }, { "includes", jsi_ArrayIncludesCmd, 1, 1, "val:any", .help="Returns true if array contains value", .retType=(uint)JSI_TT_ANY }, { "indexOf", jsi_ArrayIndexOfCmd, 1, 2, "str:any, startIdx:number=0", .help="Return index of first occurrance in array", .retType=(uint)JSI_TT_NUMBER }, { "isArray", jsi_ArrayIsArrayCmd, 0, 0, "", .help="True if val array", .retType=(uint)JSI_TT_BOOLEAN }, { "join", jsi_ArrayJoinCmd, 0, 1, "sep:string=''", .help="Return elements joined by char", .retType=(uint)JSI_TT_STRING }, { "lastIndexOf",jsi_ArrayLastindexOfCmd,1, 2, "val:any, start:number=0", .help="Return index of last occurence in array", .retType=(uint)JSI_TT_NUMBER }, { "map", jsi_ArrayMapCmd, 1, 2, "callback:function, this:object=void", .help="Creates a new array with the results of calling a provided function on every element in this array", .retType=(uint)JSI_TT_ARRAY }, { "pop", jsi_ArrayPopCmd, 0, 0, "", .help="Remove and return last element of array", .retType=(uint)JSI_TT_ANY }, { "push", jsi_ArrayPushCmd, 1,-1, "val:any, ...", .help="Push one or more elements onto array and return size", .retType=(uint)JSI_TT_NUMBER }, { "reduce", jsi_ArrayReduceCmd, 1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "reduceRight",jsi_ArrayReduceRightCmd,1, 2, "callback:function, initial:any", .help="Return a reduced array", .retType=(uint)JSI_TT_ANY }, { "shift", jsi_ArrayShiftCmd, 0, 0, "", .help="Remove first element and shift downwards", .retType=(uint)JSI_TT_ANY }, { "sizeOf", jsi_ArraySizeOfCmd, 0, 0, "", .help="Return size of array", .retType=(uint)JSI_TT_NUMBER }, { "slice", jsi_ArraySliceCmd, 1, 2, "start:number, end:number=void", .help="Return sub-array", .retType=(uint)JSI_TT_ARRAY }, { "some", jsi_ArraySomeCmd, 1, 2, "callback:function, this:object=void", .help="Return true if function returns true some element", .retType=(uint)JSI_TT_BOOLEAN }, { "sort", jsi_ArraySortCmd, 0, 1, "options:function|object=void", .help="Sort an array", .retType=(uint)JSI_TT_ARRAY, .flags=0, .info=0, .opts=jsi_ArraySortOptions }, { "splice", jsi_ArraySpliceCmd, 1,-1, "start:number, howmany:number=void, ...", .help="Change the content of an array, adding new elements while removing old elements", .retType=(uint)JSI_TT_ARRAY }, { "reverse", jsi_ArrayReverseCmd, 0, 0, "", .help="Reverse order of all elements in an array", .retType=(uint)JSI_TT_ARRAY }, { "unshift", jsi_ArrayUnshiftCmd, 0,-1, "...", .help="Add new elements to start of array and return size", .retType=(uint)JSI_TT_NUMBER }, { NULL, 0,0,0,0, .help="Provide access to array objects" } }; Jsi_RC jsi_InitArray(Jsi_Interp *interp, int release) { if (release) return JSI_OK; interp->Array_prototype = Jsi_CommandCreateSpecs(interp, "Array", arrayCmds, NULL, JSI_CMDSPEC_ISOBJ); return JSI_OK; } #endif
static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = Jsi_ObjGetLength(interp, obj); if (curlen < 0) { Jsi_ObjSetLength(interp, obj, 0); } if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj)); return JSI_OK; }
static Jsi_RC jsi_ArrayUnshiftCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,Jsi_Value **ret, Jsi_Func *funcPtr) { if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) return Jsi_LogError("expected array object"); Jsi_Obj *obj = _this->d.obj; int argc = Jsi_ValueGetLength(interp, args); int curlen = jsi_SizeOfArray(interp, obj); if (argc <= 0) { Jsi_ValueMakeNumber(interp, ret, 0); return JSI_OK; } Jsi_ObjListifyArray(interp, obj); if (Jsi_ObjArraySizer(interp, obj, curlen+argc)<=0) return Jsi_LogError("too long"); memmove(obj->arr+argc, obj->arr, (curlen)*sizeof(Jsi_Value*)); obj->arrCnt += argc; int i; for (i = 0; i < argc; ++i) { Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i); obj->arr[i] = NULL; if (!ov) { Jsi_LogBug("Arguments Error"); continue; } obj->arr[i] = ov; Jsi_IncrRefCount(interp, ov); } Jsi_ObjSetLength(interp, obj, curlen+argc); Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj)); return JSI_OK; }
{'added': [(10, 'static uint jsi_SizeOfArray(Jsi_Interp *interp, Jsi_Obj *obj) {'), (11, ' if (!obj || !obj->arr)'), (12, ' return 0;'), (13, ' return obj->arrCnt;'), (14, '}'), (15, ''), (28, ' int curlen = jsi_SizeOfArray(interp, obj);'), (36, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (50, ' int i = jsi_SizeOfArray(interp, obj) - 1;'), (83, ' curlen = jsi_SizeOfArray(interp, _this->d.obj);'), (94, ' if (0 == (argc=jsi_SizeOfArray(interp, _this->d.obj))) {'), (238, ' int len = jsi_SizeOfArray(interp, v->d.obj);'), (260, ' int i, n = 0, len = jsi_SizeOfArray(interp, arr->d.obj);'), (263, ' int clen = jsi_SizeOfArray(interp, nobj);'), (307, ' curlen = jsi_SizeOfArray(interp, obj);'), (379, ' curlen = jsi_SizeOfArray(interp, obj);'), (438, ' curlen = jsi_SizeOfArray(interp, obj);'), (614, ' int i;'), (700, ' n = jsi_SizeOfArray(interp, obj);'), (752, ' int i = jsi_SizeOfArray(interp, _this->d.obj);'), (763, ' uint n = jsi_SizeOfArray(interp, obj);'), (784, ' int curlen = jsi_SizeOfArray(interp, obj);'), (804, ' Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));'), (818, ' n = jsi_SizeOfArray(interp, obj);'), (881, ' n = jsi_SizeOfArray(interp, obj);'), (1145, ' n = jsi_SizeOfArray(interp, obj);'), (1181, ' Jsi_ObjSetLength(interp, obj, curlen=0);')], 'deleted': [(22, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (23, ' if (curlen < 0) {'), (24, ' Jsi_ObjSetLength(interp, obj, 0);'), (25, ' }'), (26, ''), (34, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (48, ' int i = Jsi_ObjGetLength(interp, obj) - 1;'), (81, ' curlen = Jsi_ObjGetLength(interp, _this->d.obj);'), (92, ' if (0 == (argc=Jsi_ObjGetLength(interp, _this->d.obj))) {'), (236, ' int len = Jsi_ObjGetLength(interp, v->d.obj);'), (258, ' int i, n = 0, len = Jsi_ObjGetLength(interp, arr->d.obj);'), (261, ' int clen = Jsi_ObjGetLength(interp, nobj);'), (305, ' curlen = Jsi_ObjGetLength(interp, obj);'), (306, ' if (curlen < 0) {'), (307, ' Jsi_ObjSetLength(interp, obj, 0);'), (308, ' }'), (380, ' curlen = Jsi_ObjGetLength(interp, obj);'), (381, ' if (curlen < 0) {'), (382, ' Jsi_ObjSetLength(interp, obj, 0);'), (383, ' }'), (442, ' curlen = Jsi_ObjGetLength(interp, obj);'), (443, ' if (curlen < 0) {'), (444, ' Jsi_ObjSetLength(interp, obj, 0);'), (445, ' }'), (525, ' int curlen;'), (538, ' curlen = Jsi_ObjGetLength(interp, obj);'), (539, ' if (curlen < 0) {'), (540, ' Jsi_ObjSetLength(interp, obj, 0);'), (541, ' }'), (569, ' int curlen;'), (582, ' curlen = Jsi_ObjGetLength(interp, obj);'), (583, ' if (curlen < 0) {'), (584, ' Jsi_ObjSetLength(interp, obj, 0);'), (585, ' }'), (631, ' int curlen, i;'), (641, ' curlen = Jsi_ObjGetLength(interp, obj);'), (642, ' if (curlen < 0)'), (643, ' Jsi_ObjSetLength(interp, obj, 0);'), (720, ' n = Jsi_ObjGetLength(interp, obj);'), (772, ' int i = Jsi_ObjGetLength(interp, _this->d.obj);'), (783, ' uint n = Jsi_ObjGetLength(interp, obj);'), (784, ' assert(n <= obj->arrCnt);'), (805, ' int curlen = Jsi_ObjGetLength(interp, obj);'), (806, ' if (curlen < 0) {'), (807, ' Jsi_ObjSetLength(interp, obj, 0);'), (808, ' }'), (828, ' Jsi_ValueMakeNumber(interp, ret, Jsi_ObjGetLength(interp, obj));'), (842, ' n = Jsi_ObjGetLength(interp, obj);'), (905, ' n = Jsi_ObjGetLength(interp, obj);'), (1169, ' n = Jsi_ObjGetLength(interp, obj);'), (1205, ' Jsi_ObjSetLength(interp, obj, 0);')]}
27
51
1,148
9,934
https://github.com/pcmacdon/jsish
CVE-2020-22875
['CWE-190']
print-802_15_4.c
ieee802_15_4_if_print
/* * Copyright (c) 2009 * Siemens AG, All rights reserved. * Dmitry Eremin-Solenikov (dbaryshkov@gmail.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IEEE 802.15.4 printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static const char *ftypes[] = { "Beacon", /* 0 */ "Data", /* 1 */ "ACK", /* 2 */ "Command", /* 3 */ "Reserved (0x4)", /* 4 */ "Reserved (0x5)", /* 5 */ "Reserved (0x6)", /* 6 */ "Reserved (0x7)", /* 7 */ }; /* * Frame Control subfields. */ #define FC_FRAME_TYPE(fc) ((fc) & 0x7) #define FC_SECURITY_ENABLED 0x0008 #define FC_FRAME_PENDING 0x0010 #define FC_ACK_REQUEST 0x0020 #define FC_PAN_ID_COMPRESSION 0x0040 #define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3) #define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3) #define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3) #define FC_ADDRESSING_MODE_NONE 0x00 #define FC_ADDRESSING_MODE_RESERVED 0x01 #define FC_ADDRESSING_MODE_SHORT 0x02 #define FC_ADDRESSING_MODE_LONG 0x03 u_int ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; }
/* * Copyright (c) 2009 * Siemens AG, All rights reserved. * Dmitry Eremin-Solenikov (dbaryshkov@gmail.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IEEE 802.15.4 printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static const char *ftypes[] = { "Beacon", /* 0 */ "Data", /* 1 */ "ACK", /* 2 */ "Command", /* 3 */ "Reserved (0x4)", /* 4 */ "Reserved (0x5)", /* 5 */ "Reserved (0x6)", /* 6 */ "Reserved (0x7)", /* 7 */ }; /* * Frame Control subfields. */ #define FC_FRAME_TYPE(fc) ((fc) & 0x7) #define FC_SECURITY_ENABLED 0x0008 #define FC_FRAME_PENDING 0x0010 #define FC_ACK_REQUEST 0x0020 #define FC_PAN_ID_COMPRESSION 0x0040 #define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3) #define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3) #define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3) #define FC_ADDRESSING_MODE_NONE 0x00 #define FC_ADDRESSING_MODE_RESERVED 0x01 #define FC_ADDRESSING_MODE_SHORT 0x02 #define FC_ADDRESSING_MODE_LONG 0x03 u_int ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; }
ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; }
ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; }
{'added': [(144, '\t\t\tND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));')], 'deleted': [(144, '\t\t\tND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2)));')]}
1
1
146
732
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13000
['CWE-125']
print-pgm.c
pgm_print
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Andy Heffernan (ahh@juniper.net) */ /* \summary: Pragmatic General Multicast (PGM) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "addrtostr.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" #include "af.h" /* * PGM header (RFC 3208) */ struct pgm_header { uint16_t pgm_sport; uint16_t pgm_dport; uint8_t pgm_type; uint8_t pgm_options; uint16_t pgm_sum; uint8_t pgm_gsid[6]; uint16_t pgm_length; }; struct pgm_spm { uint32_t pgms_seq; uint32_t pgms_trailseq; uint32_t pgms_leadseq; uint16_t pgms_nla_afi; uint16_t pgms_reserved; /* ... uint8_t pgms_nla[0]; */ /* ... options */ }; struct pgm_nak { uint32_t pgmn_seq; uint16_t pgmn_source_afi; uint16_t pgmn_reserved; /* ... uint8_t pgmn_source[0]; */ /* ... uint16_t pgmn_group_afi */ /* ... uint16_t pgmn_reserved2; */ /* ... uint8_t pgmn_group[0]; */ /* ... options */ }; struct pgm_ack { uint32_t pgma_rx_max_seq; uint32_t pgma_bitmap; /* ... options */ }; struct pgm_poll { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_reserved; /* ... options */ }; struct pgm_polr { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_subtype; uint16_t pgmp_nla_afi; uint16_t pgmp_reserved; /* ... uint8_t pgmp_nla[0]; */ /* ... options */ }; struct pgm_data { uint32_t pgmd_seq; uint32_t pgmd_trailseq; /* ... options */ }; typedef enum _pgm_type { PGM_SPM = 0, /* source path message */ PGM_POLL = 1, /* POLL Request */ PGM_POLR = 2, /* POLL Response */ PGM_ODATA = 4, /* original data */ PGM_RDATA = 5, /* repair data */ PGM_NAK = 8, /* NAK */ PGM_NULLNAK = 9, /* Null NAK */ PGM_NCF = 10, /* NAK Confirmation */ PGM_ACK = 11, /* ACK for congestion control */ PGM_SPMR = 12, /* SPM request */ PGM_MAX = 255 } pgm_type; #define PGM_OPT_BIT_PRESENT 0x01 #define PGM_OPT_BIT_NETWORK 0x02 #define PGM_OPT_BIT_VAR_PKTLEN 0x40 #define PGM_OPT_BIT_PARITY 0x80 #define PGM_OPT_LENGTH 0x00 #define PGM_OPT_FRAGMENT 0x01 #define PGM_OPT_NAK_LIST 0x02 #define PGM_OPT_JOIN 0x03 #define PGM_OPT_NAK_BO_IVL 0x04 #define PGM_OPT_NAK_BO_RNG 0x05 #define PGM_OPT_REDIRECT 0x07 #define PGM_OPT_PARITY_PRM 0x08 #define PGM_OPT_PARITY_GRP 0x09 #define PGM_OPT_CURR_TGSIZE 0x0A #define PGM_OPT_NBR_UNREACH 0x0B #define PGM_OPT_PATH_NLA 0x0C #define PGM_OPT_SYN 0x0D #define PGM_OPT_FIN 0x0E #define PGM_OPT_RST 0x0F #define PGM_OPT_CR 0x10 #define PGM_OPT_CRQST 0x11 #define PGM_OPT_PGMCC_DATA 0x12 #define PGM_OPT_PGMCC_FEEDBACK 0x13 #define PGM_OPT_MASK 0x7f #define PGM_OPT_END 0x80 /* end of options marker */ #define PGM_MIN_OPT_LEN 4 void pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); return; } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); return; } } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: #define PGM_OPT_LENGTH_LEN (2+2) if (opt_len != PGM_OPT_LENGTH_LEN) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]", opt_len, PGM_OPT_LENGTH_LEN)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += 2; opts_len -= PGM_OPT_LENGTH_LEN; break; case PGM_OPT_FRAGMENT: #define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4) if (opt_len != PGM_OPT_FRAGMENT_LEN) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]", opt_len, PGM_OPT_FRAGMENT_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; offset = EXTRACT_32BITS(bp); bp += 4; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= PGM_OPT_FRAGMENT_LEN; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= 4; /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < 4) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, 4); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += 4; opt_len -= 4; opts_len -= 4; } break; case PGM_OPT_JOIN: #define PGM_OPT_JOIN_LEN (2+2+4) if (opt_len != PGM_OPT_JOIN_LEN) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]", opt_len, PGM_OPT_JOIN_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= PGM_OPT_JOIN_LEN; break; case PGM_OPT_NAK_BO_IVL: #define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_IVL_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_IVL_LEN; break; case PGM_OPT_NAK_BO_RNG: #define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_RNG_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_RNG_LEN; break; case PGM_OPT_REDIRECT: #define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2) if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", PGM_OPT_REDIRECT_FIXED_LEN, opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: #define PGM_OPT_PARITY_PRM_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_PRM_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]", opt_len, PGM_OPT_PARITY_PRM_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= PGM_OPT_PARITY_PRM_LEN; break; case PGM_OPT_PARITY_GRP: #define PGM_OPT_PARITY_GRP_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_GRP_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]", opt_len, PGM_OPT_PARITY_GRP_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= PGM_OPT_PARITY_GRP_LEN; break; case PGM_OPT_CURR_TGSIZE: #define PGM_OPT_CURR_TGSIZE_LEN (2+2+4) if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]", opt_len, PGM_OPT_CURR_TGSIZE_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= PGM_OPT_CURR_TGSIZE_LEN; break; case PGM_OPT_NBR_UNREACH: #define PGM_OPT_NBR_UNREACH_LEN (2+2) if (opt_len != PGM_OPT_NBR_UNREACH_LEN) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]", opt_len, PGM_OPT_NBR_UNREACH_LEN)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= PGM_OPT_NBR_UNREACH_LEN; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: #define PGM_OPT_SYN_LEN (2+2) if (opt_len != PGM_OPT_SYN_LEN) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]", opt_len, PGM_OPT_SYN_LEN)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= PGM_OPT_SYN_LEN; break; case PGM_OPT_FIN: #define PGM_OPT_FIN_LEN (2+2) if (opt_len != PGM_OPT_FIN_LEN) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]", opt_len, PGM_OPT_FIN_LEN)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= PGM_OPT_FIN_LEN; break; case PGM_OPT_RST: #define PGM_OPT_RST_LEN (2+2) if (opt_len != PGM_OPT_RST_LEN) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]", opt_len, PGM_OPT_RST_LEN)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= PGM_OPT_RST_LEN; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: #define PGM_OPT_CRQST_LEN (2+2) if (opt_len != PGM_OPT_CRQST_LEN) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]", opt_len, PGM_OPT_CRQST_LEN)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= PGM_OPT_CRQST_LEN; break; case PGM_OPT_PGMCC_DATA: #define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: #define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) { ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); }
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Andy Heffernan (ahh@juniper.net) */ /* \summary: Pragmatic General Multicast (PGM) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "addrtostr.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" #include "af.h" /* * PGM header (RFC 3208) */ struct pgm_header { uint16_t pgm_sport; uint16_t pgm_dport; uint8_t pgm_type; uint8_t pgm_options; uint16_t pgm_sum; uint8_t pgm_gsid[6]; uint16_t pgm_length; }; struct pgm_spm { uint32_t pgms_seq; uint32_t pgms_trailseq; uint32_t pgms_leadseq; uint16_t pgms_nla_afi; uint16_t pgms_reserved; /* ... uint8_t pgms_nla[0]; */ /* ... options */ }; struct pgm_nak { uint32_t pgmn_seq; uint16_t pgmn_source_afi; uint16_t pgmn_reserved; /* ... uint8_t pgmn_source[0]; */ /* ... uint16_t pgmn_group_afi */ /* ... uint16_t pgmn_reserved2; */ /* ... uint8_t pgmn_group[0]; */ /* ... options */ }; struct pgm_ack { uint32_t pgma_rx_max_seq; uint32_t pgma_bitmap; /* ... options */ }; struct pgm_poll { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_reserved; /* ... options */ }; struct pgm_polr { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_subtype; uint16_t pgmp_nla_afi; uint16_t pgmp_reserved; /* ... uint8_t pgmp_nla[0]; */ /* ... options */ }; struct pgm_data { uint32_t pgmd_seq; uint32_t pgmd_trailseq; /* ... options */ }; typedef enum _pgm_type { PGM_SPM = 0, /* source path message */ PGM_POLL = 1, /* POLL Request */ PGM_POLR = 2, /* POLL Response */ PGM_ODATA = 4, /* original data */ PGM_RDATA = 5, /* repair data */ PGM_NAK = 8, /* NAK */ PGM_NULLNAK = 9, /* Null NAK */ PGM_NCF = 10, /* NAK Confirmation */ PGM_ACK = 11, /* ACK for congestion control */ PGM_SPMR = 12, /* SPM request */ PGM_MAX = 255 } pgm_type; #define PGM_OPT_BIT_PRESENT 0x01 #define PGM_OPT_BIT_NETWORK 0x02 #define PGM_OPT_BIT_VAR_PKTLEN 0x40 #define PGM_OPT_BIT_PARITY 0x80 #define PGM_OPT_LENGTH 0x00 #define PGM_OPT_FRAGMENT 0x01 #define PGM_OPT_NAK_LIST 0x02 #define PGM_OPT_JOIN 0x03 #define PGM_OPT_NAK_BO_IVL 0x04 #define PGM_OPT_NAK_BO_RNG 0x05 #define PGM_OPT_REDIRECT 0x07 #define PGM_OPT_PARITY_PRM 0x08 #define PGM_OPT_PARITY_GRP 0x09 #define PGM_OPT_CURR_TGSIZE 0x0A #define PGM_OPT_NBR_UNREACH 0x0B #define PGM_OPT_PATH_NLA 0x0C #define PGM_OPT_SYN 0x0D #define PGM_OPT_FIN 0x0E #define PGM_OPT_RST 0x0F #define PGM_OPT_CR 0x10 #define PGM_OPT_CRQST 0x11 #define PGM_OPT_PGMCC_DATA 0x12 #define PGM_OPT_PGMCC_FEEDBACK 0x13 #define PGM_OPT_MASK 0x7f #define PGM_OPT_END 0x80 /* end of options marker */ #define PGM_MIN_OPT_LEN 4 void pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); } return; } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); ND_TCHECK_16BITS(bp); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: #define PGM_OPT_LENGTH_LEN (2+2) if (opt_len != PGM_OPT_LENGTH_LEN) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]", opt_len, PGM_OPT_LENGTH_LEN)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += 2; opts_len -= PGM_OPT_LENGTH_LEN; break; case PGM_OPT_FRAGMENT: #define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4) if (opt_len != PGM_OPT_FRAGMENT_LEN) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]", opt_len, PGM_OPT_FRAGMENT_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; offset = EXTRACT_32BITS(bp); bp += 4; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= PGM_OPT_FRAGMENT_LEN; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= 4; /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < 4) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, 4); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += 4; opt_len -= 4; opts_len -= 4; } break; case PGM_OPT_JOIN: #define PGM_OPT_JOIN_LEN (2+2+4) if (opt_len != PGM_OPT_JOIN_LEN) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]", opt_len, PGM_OPT_JOIN_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= PGM_OPT_JOIN_LEN; break; case PGM_OPT_NAK_BO_IVL: #define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_IVL_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_IVL_LEN; break; case PGM_OPT_NAK_BO_RNG: #define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_RNG_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_RNG_LEN; break; case PGM_OPT_REDIRECT: #define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2) if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", PGM_OPT_REDIRECT_FIXED_LEN, opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: #define PGM_OPT_PARITY_PRM_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_PRM_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]", opt_len, PGM_OPT_PARITY_PRM_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= PGM_OPT_PARITY_PRM_LEN; break; case PGM_OPT_PARITY_GRP: #define PGM_OPT_PARITY_GRP_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_GRP_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]", opt_len, PGM_OPT_PARITY_GRP_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= PGM_OPT_PARITY_GRP_LEN; break; case PGM_OPT_CURR_TGSIZE: #define PGM_OPT_CURR_TGSIZE_LEN (2+2+4) if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]", opt_len, PGM_OPT_CURR_TGSIZE_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= PGM_OPT_CURR_TGSIZE_LEN; break; case PGM_OPT_NBR_UNREACH: #define PGM_OPT_NBR_UNREACH_LEN (2+2) if (opt_len != PGM_OPT_NBR_UNREACH_LEN) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]", opt_len, PGM_OPT_NBR_UNREACH_LEN)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= PGM_OPT_NBR_UNREACH_LEN; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: #define PGM_OPT_SYN_LEN (2+2) if (opt_len != PGM_OPT_SYN_LEN) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]", opt_len, PGM_OPT_SYN_LEN)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= PGM_OPT_SYN_LEN; break; case PGM_OPT_FIN: #define PGM_OPT_FIN_LEN (2+2) if (opt_len != PGM_OPT_FIN_LEN) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]", opt_len, PGM_OPT_FIN_LEN)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= PGM_OPT_FIN_LEN; break; case PGM_OPT_RST: #define PGM_OPT_RST_LEN (2+2) if (opt_len != PGM_OPT_RST_LEN) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]", opt_len, PGM_OPT_RST_LEN)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= PGM_OPT_RST_LEN; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: #define PGM_OPT_CRQST_LEN (2+2) if (opt_len != PGM_OPT_CRQST_LEN) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]", opt_len, PGM_OPT_CRQST_LEN)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= PGM_OPT_CRQST_LEN; break; case PGM_OPT_PGMCC_DATA: #define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: #define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) { ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); }
pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); return; } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); return; } } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: #define PGM_OPT_LENGTH_LEN (2+2) if (opt_len != PGM_OPT_LENGTH_LEN) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]", opt_len, PGM_OPT_LENGTH_LEN)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += 2; opts_len -= PGM_OPT_LENGTH_LEN; break; case PGM_OPT_FRAGMENT: #define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4) if (opt_len != PGM_OPT_FRAGMENT_LEN) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]", opt_len, PGM_OPT_FRAGMENT_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; offset = EXTRACT_32BITS(bp); bp += 4; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= PGM_OPT_FRAGMENT_LEN; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= 4; /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < 4) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, 4); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += 4; opt_len -= 4; opts_len -= 4; } break; case PGM_OPT_JOIN: #define PGM_OPT_JOIN_LEN (2+2+4) if (opt_len != PGM_OPT_JOIN_LEN) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]", opt_len, PGM_OPT_JOIN_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= PGM_OPT_JOIN_LEN; break; case PGM_OPT_NAK_BO_IVL: #define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_IVL_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_IVL_LEN; break; case PGM_OPT_NAK_BO_RNG: #define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_RNG_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_RNG_LEN; break; case PGM_OPT_REDIRECT: #define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2) if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", PGM_OPT_REDIRECT_FIXED_LEN, opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: #define PGM_OPT_PARITY_PRM_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_PRM_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]", opt_len, PGM_OPT_PARITY_PRM_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= PGM_OPT_PARITY_PRM_LEN; break; case PGM_OPT_PARITY_GRP: #define PGM_OPT_PARITY_GRP_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_GRP_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]", opt_len, PGM_OPT_PARITY_GRP_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= PGM_OPT_PARITY_GRP_LEN; break; case PGM_OPT_CURR_TGSIZE: #define PGM_OPT_CURR_TGSIZE_LEN (2+2+4) if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]", opt_len, PGM_OPT_CURR_TGSIZE_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= PGM_OPT_CURR_TGSIZE_LEN; break; case PGM_OPT_NBR_UNREACH: #define PGM_OPT_NBR_UNREACH_LEN (2+2) if (opt_len != PGM_OPT_NBR_UNREACH_LEN) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]", opt_len, PGM_OPT_NBR_UNREACH_LEN)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= PGM_OPT_NBR_UNREACH_LEN; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: #define PGM_OPT_SYN_LEN (2+2) if (opt_len != PGM_OPT_SYN_LEN) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]", opt_len, PGM_OPT_SYN_LEN)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= PGM_OPT_SYN_LEN; break; case PGM_OPT_FIN: #define PGM_OPT_FIN_LEN (2+2) if (opt_len != PGM_OPT_FIN_LEN) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]", opt_len, PGM_OPT_FIN_LEN)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= PGM_OPT_FIN_LEN; break; case PGM_OPT_RST: #define PGM_OPT_RST_LEN (2+2) if (opt_len != PGM_OPT_RST_LEN) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]", opt_len, PGM_OPT_RST_LEN)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= PGM_OPT_RST_LEN; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: #define PGM_OPT_CRQST_LEN (2+2) if (opt_len != PGM_OPT_CRQST_LEN) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]", opt_len, PGM_OPT_CRQST_LEN)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= PGM_OPT_CRQST_LEN; break; case PGM_OPT_PGMCC_DATA: #define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: #define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) { ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); }
pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); } return; } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); ND_TCHECK_16BITS(bp); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: #define PGM_OPT_LENGTH_LEN (2+2) if (opt_len != PGM_OPT_LENGTH_LEN) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]", opt_len, PGM_OPT_LENGTH_LEN)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += 2; opts_len -= PGM_OPT_LENGTH_LEN; break; case PGM_OPT_FRAGMENT: #define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4) if (opt_len != PGM_OPT_FRAGMENT_LEN) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]", opt_len, PGM_OPT_FRAGMENT_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; offset = EXTRACT_32BITS(bp); bp += 4; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= PGM_OPT_FRAGMENT_LEN; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= 4; /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < 4) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, 4); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += 4; opt_len -= 4; opts_len -= 4; } break; case PGM_OPT_JOIN: #define PGM_OPT_JOIN_LEN (2+2+4) if (opt_len != PGM_OPT_JOIN_LEN) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]", opt_len, PGM_OPT_JOIN_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= PGM_OPT_JOIN_LEN; break; case PGM_OPT_NAK_BO_IVL: #define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_IVL_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_IVL_LEN; break; case PGM_OPT_NAK_BO_RNG: #define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_RNG_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_RNG_LEN; break; case PGM_OPT_REDIRECT: #define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2) if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", PGM_OPT_REDIRECT_FIXED_LEN, opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: #define PGM_OPT_PARITY_PRM_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_PRM_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]", opt_len, PGM_OPT_PARITY_PRM_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= PGM_OPT_PARITY_PRM_LEN; break; case PGM_OPT_PARITY_GRP: #define PGM_OPT_PARITY_GRP_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_GRP_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]", opt_len, PGM_OPT_PARITY_GRP_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= PGM_OPT_PARITY_GRP_LEN; break; case PGM_OPT_CURR_TGSIZE: #define PGM_OPT_CURR_TGSIZE_LEN (2+2+4) if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]", opt_len, PGM_OPT_CURR_TGSIZE_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= PGM_OPT_CURR_TGSIZE_LEN; break; case PGM_OPT_NBR_UNREACH: #define PGM_OPT_NBR_UNREACH_LEN (2+2) if (opt_len != PGM_OPT_NBR_UNREACH_LEN) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]", opt_len, PGM_OPT_NBR_UNREACH_LEN)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= PGM_OPT_NBR_UNREACH_LEN; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: #define PGM_OPT_SYN_LEN (2+2) if (opt_len != PGM_OPT_SYN_LEN) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]", opt_len, PGM_OPT_SYN_LEN)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= PGM_OPT_SYN_LEN; break; case PGM_OPT_FIN: #define PGM_OPT_FIN_LEN (2+2) if (opt_len != PGM_OPT_FIN_LEN) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]", opt_len, PGM_OPT_FIN_LEN)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= PGM_OPT_FIN_LEN; break; case PGM_OPT_RST: #define PGM_OPT_RST_LEN (2+2) if (opt_len != PGM_OPT_RST_LEN) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]", opt_len, PGM_OPT_RST_LEN)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= PGM_OPT_RST_LEN; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: #define PGM_OPT_CRQST_LEN (2+2) if (opt_len != PGM_OPT_CRQST_LEN) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]", opt_len, PGM_OPT_CRQST_LEN)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= PGM_OPT_CRQST_LEN; break; case PGM_OPT_PGMCC_DATA: #define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: #define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) { ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); }
{'added': [(177, '\t\treturn;'), (364, '\t ND_TCHECK_16BITS(bp);')], 'deleted': [(172, '\t\t\treturn;'), (177, '\t\t\treturn;')]}
2
2
663
3,686
https://github.com/the-tcpdump-group/tcpdump
CVE-2017-13034
['CWE-125']
escape.c
curl_easy_escape
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Escape and unescape URL encoding in strings. The functions return a new * allocated string or NULL if an error occurred. */ #include "setup.h" #include <curl/curl.h> #include "curl_memory.h" #include "urldata.h" #include "warnless.h" #include "non-ascii.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> /* The last #include file should be: */ #include "memdebug.h" /* Portable character check (remember EBCDIC). Do not use isalnum() because its behavior is altered by the current locale. See http://tools.ietf.org/html/rfc3986#section-2.3 */ static bool Curl_isunreserved(unsigned char in) { switch (in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return TRUE; default: break; } return FALSE; } /* for ABI-compatibility with previous versions */ char *curl_escape(const char *string, int inlength) { return curl_easy_escape(NULL, string, inlength); } /* for ABI-compatibility with previous versions */ char *curl_unescape(const char *string, int length) { return curl_easy_unescape(NULL, string, length, NULL); } char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } /* * Unescapes the given URL escaped string of given length. Returns a * pointer to a malloced string with length given in *olen. * If length == 0, the length is assumed to be strlen(string). * If olen == NULL, no output length is stored. */ char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { int alloc = (length?length:(int)strlen(string))+1; char *ns = malloc(alloc); unsigned char in; int strindex=0; unsigned long hex; CURLcode res; if(!ns) return NULL; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(handle, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return NULL; } string+=2; alloc-=2; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; return ns; } /* For operating systems/environments that use different malloc/free systems for the app and for this library, we provide a free that uses the library's memory system */ void curl_free(void *p) { if(p) free(p); }
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Escape and unescape URL encoding in strings. The functions return a new * allocated string or NULL if an error occurred. */ #include "setup.h" #include <curl/curl.h> #include "curl_memory.h" #include "urldata.h" #include "warnless.h" #include "non-ascii.h" #include "escape.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> /* The last #include file should be: */ #include "memdebug.h" /* Portable character check (remember EBCDIC). Do not use isalnum() because its behavior is altered by the current locale. See http://tools.ietf.org/html/rfc3986#section-2.3 */ static bool Curl_isunreserved(unsigned char in) { switch (in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return TRUE; default: break; } return FALSE; } /* for ABI-compatibility with previous versions */ char *curl_escape(const char *string, int inlength) { return curl_easy_escape(NULL, string, inlength); } /* for ABI-compatibility with previous versions */ char *curl_unescape(const char *string, int length) { return curl_easy_unescape(NULL, string, length, NULL); } char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; size_t strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } /* * Curl_urldecode() URL decodes the given string. * * Optionally detects control characters (byte codes lower than 32) in the * data and rejects such data. * * Returns a pointer to a malloced string in *ostring with length given in * *olen. If length == 0, the length is assumed to be strlen(string). * */ CURLcode Curl_urldecode(struct SessionHandle *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string))+1; char *ns = malloc(alloc); unsigned char in; size_t strindex=0; unsigned long hex; CURLcode res; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(data, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return res; } string+=2; alloc-=2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; if(ostring) /* store output string */ *ostring = ns; return CURLE_OK; } /* * Unescapes the given URL escaped string of given length. Returns a * pointer to a malloced string with length given in *olen. * If length == 0, the length is assumed to be strlen(string). * If olen == NULL, no output length is stored. */ char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { char *str = NULL; size_t inputlen = length; size_t outputlen; CURLcode res = Curl_urldecode(handle, string, inputlen, &str, &outputlen, FALSE); if(res) return NULL; if(olen) *olen = curlx_uztosi(outputlen); return str; } /* For operating systems/environments that use different malloc/free systems for the app and for this library, we provide a free that uses the library's memory system */ void curl_free(void *p) { if(p) free(p); }
char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; }
char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; size_t strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; }
{'added': [(34, '#include "escape.h"'), (88, ' size_t strindex=0;'), (136, ' * Curl_urldecode() URL decodes the given string.'), (137, ' *'), (138, ' * Optionally detects control characters (byte codes lower than 32) in the'), (139, ' * data and rejects such data.'), (140, ' *'), (141, ' * Returns a pointer to a malloced string in *ostring with length given in'), (142, ' * *olen. If length == 0, the length is assumed to be strlen(string).'), (143, ' *'), (145, 'CURLcode Curl_urldecode(struct SessionHandle *data,'), (146, ' const char *string, size_t length,'), (147, ' char **ostring, size_t *olen,'), (148, ' bool reject_ctrl)'), (150, ' size_t alloc = (length?length:strlen(string))+1;'), (153, ' size_t strindex=0;'), (158, ' return CURLE_OUT_OF_MEMORY;'), (174, ' res = Curl_convert_from_network(data, &in, 1);'), (178, ' return res;'), (184, ' if(reject_ctrl && (in < 0x20)) {'), (185, ' free(ns);'), (186, ' return CURLE_URL_MALFORMAT;'), (187, ' }'), (197, ''), (198, ' if(ostring)'), (199, ' /* store output string */'), (200, ' *ostring = ns;'), (201, ''), (202, ' return CURLE_OK;'), (203, '}'), (204, ''), (205, '/*'), (206, ' * Unescapes the given URL escaped string of given length. Returns a'), (207, ' * pointer to a malloced string with length given in *olen.'), (208, ' * If length == 0, the length is assumed to be strlen(string).'), (209, ' * If olen == NULL, no output length is stored.'), (210, ' */'), (211, 'char *curl_easy_unescape(CURL *handle, const char *string, int length,'), (212, ' int *olen)'), (213, '{'), (214, ' char *str = NULL;'), (215, ' size_t inputlen = length;'), (216, ' size_t outputlen;'), (217, ' CURLcode res = Curl_urldecode(handle, string, inputlen, &str, &outputlen,'), (218, ' FALSE);'), (219, ' if(res)'), (220, ' return NULL;'), (221, ' if(olen)'), (222, ' *olen = curlx_uztosi(outputlen);'), (223, ' return str;')], 'deleted': [(87, ' int strindex=0;'), (135, ' * Unescapes the given URL escaped string of given length. Returns a'), (136, ' * pointer to a malloced string with length given in *olen.'), (137, ' * If length == 0, the length is assumed to be strlen(string).'), (138, ' * If olen == NULL, no output length is stored.'), (140, 'char *curl_easy_unescape(CURL *handle, const char *string, int length,'), (141, ' int *olen)'), (143, ' int alloc = (length?length:(int)strlen(string))+1;'), (146, ' int strindex=0;'), (151, ' return NULL;'), (167, ' res = Curl_convert_from_network(handle, &in, 1);'), (171, ' return NULL;'), (186, ' return ns;')]}
50
13
147
879
https://github.com/bagder/curl
CVE-2012-0036
['CWE-89']